BubbleSort and Insertion sort

mrnutty 1 Tallied Votes 432 Views Share

The simplest sort, although inefficient. Below is a demonstration of
bubble sort and insertion sort.

The bubble sort just consists of 2 for loops and std::swap.

The insertion sort uses 2 loops as well but not as much swap
as bubble sort.

Any questions ?

Ancient Dragon commented: Great job :) +25
#include <iostream>
#include <algorithm>
#include <ctime>

using std::cout;
using std::cin;
using std::endl;

//sort lower to higher
//note: very bad but very simple,just 2 for loops and std::swap function
// blindly swaps content
void bubbleSort(int Array[], const int arraySize)
{
	for(int compareNumIndex = 0 ; compareNumIndex < arraySize; compareNumIndex++)
	{
		for(int checkNumIndex = compareNumIndex + 1; checkNumIndex < arraySize; checkNumIndex++)
		{
			if(Array[compareNumIndex] > Array[checkNumIndex]) // swap if bigger
				std::swap(Array[compareNumIndex],Array[checkNumIndex]);
		}
	}
}
//not bad for arraySize <= around 30
//Idea : find max swap it to next end index
void selectionSort(int Array[],const int arraySize)
{
	int minIndex = 0;

	for(int strt = 0;  strt < arraySize; strt++)
	{
		minIndex = strt; //new min index

		for(int compIndx = strt+1; compIndx < arraySize; compIndx++)	{ //find min index
			if(Array[minIndex] > Array[compIndx])
				minIndex = compIndx;
		}
		//now minIndex points to the smallest element
		//just swap it at the current beginning
		std::swap(Array[minIndex],Array[strt]);
	}
}
void print(int Array[], const int size)
{
	for(int i = 0; i < size; i++)
		cout << Array[i] << " ";
	
	cout<<endl<<endl;
}
int main()
{
	srand(time(0));

	int Array1[10] = {0};
	int Array2[10] = {0};
	//populate with random numbers
	for(int i = 0; i < 10; i++){
		Array1[i] = rand() % 100;
		Array2[i] = rand() % 100;
	}

	cout<<"Original content in Array1 : ";
	print(Array1,10);
	cout<<"After being sorted by bubble sort : ";
	bubbleSort(Array1,10);
	print(Array1,10);

	cout<<"\n\nOriginal content in Array2 : ";
	print(Array2,10);
	cout<<"After being sorted by selection sort : ";
	selectionSort(Array2,10);
	print(Array2,10);

	cout<<"\n\n";

	return 0;	
}
Nick Evan 4,005 Industrious Poster Team Colleague Featured Poster

Selection-sort is not the same thing as insertion-sort ;)

mrnutty 761 Senior Poster

Ok, I got my terminology mixed up. Was thinking insertion but wrote selection.

88omar 0 Light Poster

How would you go about combining Insertion sort and Selection sort thou, using the same method?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.