首页 > 代码库 > 快速排序算法

快速排序算法

      快速排序算法(quick sort)是对冒泡排序的一种改进,是目前内部排序中速度最快的一种排序方法。

基本思想是:通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字比另一部分记录的关键字小,则可对这两部分记录分别继续进行排序,以达到整个序列有序。

      整个算法的时间复杂度是:O(nlog2n).

      算法的实现代码如下:

 1 #include <stdio.h> 2  3 /**************************************************** 4 **function:    print 5 **description: print the element 6 **intput:      the array 7 **return:      void 8 ****************************************************/ 9 void print(int array[])10 {11     int i;12     13     for(i = 0; i < 8; i++)14     {15         printf("%d ", array[i]);16     }17 }18 /****************************************************19 **function:    quicksort20 **description: detach the array into two parts21 **intput:      the array, low, high22 **return:      the position of the key23 ****************************************************/24 int quicksort(int a[], int low, int high)25 {26     int key = a[low];27 28     while(low < high)29     {30         while(low < high && a[high] >= key) high--;31         a[low] = a[high];    /* exchange the value*/32         while(low < high && a[low] < key) low++;33         a[high] = a[low];    /* exchange the value*/34     }35     a[low] = key;             /* the last value*/36     return low;37 }38 /****************************************************39 **function:    qsort40 **description: sort the array 41 **intput:      the array, low, high42 **return:      void43 ****************************************************/44 void qsort(int a[], int low, int high)45 {46     int pivot;47     if (low < high)48     {49         pivot = quicksort(a, low, high);50         qsort(a, low, pivot-1);       /*deal the first part */51         qsort(a, pivot+1, high);     /*deal the second part */52     }53 }54 /* test the code */55 void qsorttest(int a[], int low, int high)56 {57     qsort(a, low, high);58     print(a);59 }60 61 int main(int argc, char *argv[])62 {63     int array[] = {11, 34, 23, 7, 21, 13, 9, 81};64     qsorttest(array, 0, 7);65     return (0);66 }67 68 /**********************end file****************************/

     

快速排序算法