快速排序

1.算法介绍

  通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

2.算法原理

  1)选择一个基准元素,通常选择第一个元素或者最后一个元素,

  2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。

  3)此时基准元素在其排好序后的正确位置

  4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。

3.源代码

 1 void print(int a[], int n){  
 2     for(int j= 0; j<n; j++){  
 3         cout<<a[j] <<"  ";  
 4     }  
 5     cout<<endl;  
 6 }  
 7   
 8 void swap(int *a, int *b)  
 9 {  
10     int tmp = *a;  
11     *a = *b;  
12     *b = tmp;  
13 }  
14   
15 int partition(int a[], int low, int high)  
16 {  
17     int privotKey = a[low];                             //基准元素  
18     while(low < high){                                   //从表的两端交替地向中间扫描  
19         while(low < high  && a[high] >= privotKey) --high;  //从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端  
20         swap(&a[low], &a[high]);  
21         while(low < high  && a[low] <= privotKey ) ++low;  
22         swap(&a[low], &a[high]);  
23     }  
24     print(a,10);  
25     return low;  
26 }  
27   
28   
29 void quickSort(int a[], int low, int high){  
30     if(low < high){  
31         int privotLoc = partition(a,  low,  high);  //将表一分为二  
32         quickSort(a,  low,  privotLoc -1);          //递归对低子表递归排序  
33         quickSort(a,   privotLoc + 1, high);        //递归对高子表递归排序  
34     }  
35 }  
36   
37 int main(){  
38     int a[10] = {3,1,5,7,2,4,9,6,10,8};  
39     cout<<"初始值:";  
40     print(a,10);  
41     quickSort(a,0,9);  
42     cout<<"结果:";  
43     print(a,10);  
44   
45 }  

4.时间复杂度

  O(nlgn)

posted @ 2015-07-12 19:46  某某璀  阅读(201)  评论(0编辑  收藏  举报
levels of contents