见此代码,输出了几种排序方法的运行时长

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 10000
void swap(int *a, int *b){int tmp;tmp=*a;*a = *b;*b = tmp;}
void rand_Array(int Array[]){for (int i = 0; i < MAXSIZE; i++)Array[i] = rand();}
void selection_sort(int a[],int l, int r)
{
for (int i = l; i <= r; i++)
{
int min = i;
for (int j = i + 1; j <= r; j++) //走访未排序的元素
if (a[j] < a[min])
min = j; //找到目前最小值
swap(&a[min], &a[i]); //做交換
}
}
void insertion_sort(int a[],int l, int r)
{
for (int i = l + 1; i <= r; i++)
{
int key = a[i];
int j = i - 1;
while ((j >= 0) && (key < a[j]))
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
void bubble_sort(int a[],int l,int r)
{
for (int i = l; i <= r; i++)
for (int j = l; j <= r - i; j++)
if (a[j] > a[j + 1])
swap(&a[j], &a[j+1]);
}
void quick_sort(int a[],int l, int r)
{
int i = l, j = r, mid = a[(l + r) / 2]; //将当前序列在中间位置的数定义为分隔数
do
{
while (a[i] < mid)i++; //在左半部分寻找比中间数大的数
while (a[j] > mid)j--; //在右半部分寻找比中间数小的数
if (i <= j)
{
swap(&a[i], &a[j]);//若找到一组与排序目标不一致的数对则交换它们
i++;
j--; //继续找
}
} while (i <= j); //注意这里不能有等号
if (l < j) quick_sort(a,l,j); //若未到两个数的边界,则递归搜索左右区间
if (i < r) quick_sort(a,i,r);
}
int main()
{
int Array[MAXSIZE];
clock_t start,end;

rand_Array(Array);
start=clock();
insertion_sort(Array,0,MAXSIZE-1);
end=clock();
printf("insertion_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC);

rand_Array(Array);
start=clock();
selection_sort(Array,0,MAXSIZE-1);
end=clock();
printf("selection_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC);

rand_Array(Array);
start=clock();
bubble_sort(Array,0,MAXSIZE-1);
end=clock();
printf("bubble_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC);

rand_Array(Array);
start=clock();
quick_sort(Array,0,MAXSIZE-1);
end=clock();
printf("quick_sort runs in %lf seconds\n",(double)(end-start)/CLOCKS_PER_SEC);
}

// system("ping -n 4 127.0.0.1 ");
// for (int i = 0; i < MAXSIZE; i++)printf("%d ",Array[i]);