Complexity of Sorting
Complexity of Sorting
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
long length = 1000;
const long max_length = 1000000;
int list[max_length];
void read() {
ifstream fin("random.dat", ios::binary);
for (long i = 0; i < length; i++){
fin.read((char*)&list[i], sizeof(int));
}
fin.close();
}
void insertionSort() {
int temp;
for(long i = 1; i < length; i++) {
temp = list[i];
long j;
for(j = i-1; j >= 0 && list[j] > temp; j--){
list[j+1] = list[j];
}
list[j+1] = temp;
}
}
void mergesort(long low,long mid,long high) {
int t[100000];
long i,j,k;
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high)) {
if(list[i]>=list[j])
t[k++]=list[j++];
else
t[k++]=list[i++];
}
while(i<=mid)
t[k++]=list[i++];
while(j<=high)
t[k++]=list[j++];
for(i=low;i<=high;i++)
list[i]=t[i];
}
void msortdiv(long low,long high) {
long mid;
if(low!=high) {
mid=((low+high)/2);
msortdiv(low,mid);
msortdiv(mid+1,high);
mergesort(low,mid,high);
}
}
int main()
{ double t1, t2;
for (length = 1000; length <= max_length; ) {
cout << "\nLength\t: " << length << '\n';
read();
t1 = clock();
msortdiv(0, length - 1);
t2 = clock();
cout << "mergesort\t: " << (t2 - t1)/CLK_TCK << " sec\n";
read();
t1 = clock();
insertionSort();
t2 = clock();
cout << "Insertion Sort\t: " << (t2 - t1)/CLK_TCK << " sec\n";
switch (length){
case 1000 :
length = 10000;
break;
case 10000 :
length = 100000;
break;
case 100000 :
length = 1000000;
break;
case 1000000 :
length = 10000001;
break;
}
}
return 0;
}
Input
1000
10000
100000
1000000
Merge
Insertion sort
sort
0.003
0.28
24.995
1016.4
0.005
0.035
0.308
0.453
Insertion sort
600
mergesort
400
200
0
1000
10000
100000
INPUT (N)
1000000
Improved
Insertion sort
Input
1000
insertion
0.04
0.03
10000
0.272
0.226
10000
0
10000
00
22.852
16.297
1011.1
950.6
Insertion sort
600
400
200
0
1000
10000
100000
INPUT (N)
1000000
return partition(p,r);
}
void quickSort(long left, long right) {
break;
case 1000000 :
length = 10000001;
break;
} }
return 0; }
Input
Quick sort
1000
10000
100000
1000000
1739
24634
319425
3453887
1740
24649
319268
3334843
Number of exchanges
4000000
3500000
3000000
2500000
2000000
1500000
1000000
500000
0
Quick sort
Randomized quick sort
INPUT (N)