對比元素個數30000時,冒泡排序法和快速排序法算法的實際耗時
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef int KeyType;
typedef struct {
KeyType Key;
}DataType;
void BubbleSort(DataType a[], int n)
//對數據元素a[0]-a[n-1]進行冒泡排序
{
int i, j, flag = 1;
DataType temp;
for (i = 1; i < n&&flag == 1; i++) {
flag = 0;
for (j = 0; j <n-i;j++) {
if (a[j].Key>a[j+1].Key) {
flag = 1;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
void QuickSort(DataType a[], int low, int high)
//用遞歸的方法對數據元素a[low]-a[high]進行快速排序
{
int i = low, j = high;
DataType temp = a[low];//取第一個數據元素爲進行調整的標準數據元素
while (i < j) {
while (i < j&&temp.Key <= a[j].Key)
j--;//在數組的右端掃描
if (i < j) {
a[i] = a[j];
i++;
}
while (i < j&&a[i].Key < temp.Key)
i++;//在數組的左端進行掃描
if (i < j) {
a[j] = a[i];
j--;
}
}
a[i] = temp;
if (low < i)
QuickSort(a, low,i-1);//對左端子集合進行遞歸
if (i < high)
QuickSort(a, j + 1, high);//對右端子集合進行遞歸
}
void main() {
int i, n = 30000;
double dif;
time_t start, end;
DataType test1[30000], test2[30000];
for (i = 0; i < n; i++) {
test1[i].Key = rand();
//隨機生成測試數據
test2[i].Key = test1[i].Key;
//準備兩組相同數據
}
//冒泡排序測試
time(&start);
//起始時間
BubbleSort(test1, n);
//實際運行冒泡排序函數
time(&end);
//結束時間
dif = difftime(end, start);
//計算耗時
printf("冒泡排序用時:%.2f秒\n", dif);
//輸出顯示實際耗時
//快速排序測試
time(&start);
//起始時間
QuickSort(test2, 0, n - 1);
//運行快速排序算法
time(&end);
//結束時間
dif = difftime(end, start);
//計算耗時
printf("快速排序用時:%.2f秒\n", dif);
//輸出顯示實際耗時
system("pause");
}
理論分析當數據元素個數足夠大的時候,快速排序法優於冒泡排序法。這與理論估計的結果是一樣的。
*Rand函數爲隨機數生成函數,在頭文件stdib.h中。
**Time函數的功能爲取系統當前時間,difftime(end,start)函數求的是時間差。