954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

BubbleSort and Insertion sort

By D.Chhetri on Nov 22nd, 2009 10:33 am

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 ?

#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;	
}

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

Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

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

firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

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

88omar
Light Poster
35 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You