I ran my program using qsort( ) , then again using sort( ).But qsort( ) finished faster than sort( ).why is that?
Code:
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<ctime>
using namespace std;
int compare(const void * a, const void * b)
{
return (*(int*)a - *(int*)b);
}
void fillRand(int* a, size_t size, int low, int high)
{
srand(time(NULL));
int i;
for (i = 0; i<size; ++i)
{
a[i] = rand() % ((high + 1) - low) + low;
}
}
int main()
{
size_t size; cout << " size : "; cin >> size;
int* a = new int[size];
int l, h; cout << " low : "; cin >> l; cout << " high : "; cin >> h;
fillRand(a, size, l, h);
clock_t st, et;
double diff;
char answer;
int option;
cout << " Which sorting method would you like to apply : \n"
<< " 1.qsort()\n"
<< " 2.sort()\n ";
cin >> option;
if (option == 1)
{
st = clock();
qsort(a, size, sizeof(int), compare);
et = clock();
diff = et - st;
cout << " time taken = " << diff / CLOCKS_PER_SEC << " sec" << endl;
}
else if (option == 2)
{
st = clock();
sort(a, a + size);
et = clock();
diff = et - st;
cout << " time taken = " << diff / CLOCKS_PER_SEC << " sec" << endl;
}
else
{
cout << " Invalid option\n";
exit(0);
}
delete[] a;
return 0;
}