1

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 ?

Votes + Comments
Great job :)
#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;	
}
3
Contributors
3
Replies
6
Views
7 Years
Discussion Span
Last Post by 88omar
0

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

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.