Nick Evan
Not a Llama
Moderator
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
#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;
}