Hey guys,
I need to write a C++ program that use to compare sorting algorithm. I've tried to implement counter on each of <.>, = operations I've encounter in the function (currently i am working on selection sort), however the sum of the counter doesn't really match big O selection sort equation which is O=(n^2)
right now if n = 10 gives result of 64
My problem is I am unsure where to insert my counter in my function to counts the comparison properly?
I'll attach my program below
Thanks heaps for your help =D
#include <iostream>
#include <time.h>
using namespace std;
int data[5000];
int first[5000];
int second[5000];
int co=0;
void selectionSort(int count);
void BubbleSort(int count);
void fillArray(int count);
void swap(int & m, int & n);
void printArray(int count, int input[]);
void swap(int & m, int & n){
int temp = m;
m = n;
n = temp;
//co++;
}
void fillArray(int count){
int i;
// example theres 10 element inside the array
for(i=0;i < count; i++){
data[i] = rand();
//cout << data[i] << endl;
}
}
void selectionSort(int count){
//select the smallest number and swap it to the front
int pass, i, min;
for(pass=0; pass<count-1;pass++){
min = pass;
co++;
for(i = pass+1; i < count; i++){
co++;
if(data[i] < data[min]){
min = i;
co++;
}
}
swap(data[min],data[pass]);
}
}
void BubbleSort(int count){
bool swapping;
int i;
swapping = true;
while (swapping) {
swapping = false;
for (i = 0; i < count - 1; i++) { // don’t look at the last one
if (data[i] > data[i + 1]) { // a comparison here
swap(data[i], data[i + 1]);
swapping = true;
}
}
}
}
void printArray(int count, int input[]){
int i;
for(i=0;i<count;i++){
cout <<input[i] << endl;
}
}
void halfArray(int count){
int i, n;
for(i=0;i<count;i++){
for(n=0;n<count/2;n++){
first[n]=data[n];
}
second[i] = data[n+i];
}
}
int main(){
//fillArray(10);
selectionSort(10);
//BubbleSort(10);
//printArray(10,data);
cout << co << endl;
}