冒泡排序法与快速排序法对比

对比元素个数30000时,冒泡排序法和快速排序法算法的实际耗时

#include

#include

#include

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)函数求的是时间差。

 

你可能感兴趣的:(算法)