演算法之快速排序

來源:互聯網
上載者:User

標籤:style   blog   color   os   strong   io   for   art   

快速排序 是1962年提出的一種劃分交換排序。它採用了一種分治的策略,通常稱為分治法 (Divide-and-Conquer Method)。


分治法的基本思想 :
將原問題分解為若干個規模更小但結構與原問題相似的子問題。遞迴地解這些子問題,然後將這些子問題的解組合為原問題的解。


快速排序的基本思想 :
設當前待排序的無序區為R[low..high],利用分治法可將快速排序的基本思想描述為:
(1) 分解 
在R[low..high]中任選一個記錄作為基準(Pivot),以此基準將當前無序區劃分為左、右兩個較小的子區間R[low..pivotpos-1]和R[pivotpos+1..high],並使 左邊子區間中所有記錄的關鍵字均<=基準記錄的關鍵字pivot.key,右邊的子區間中所有記錄的關鍵字均>=pivot.key,而基準記錄pivot則位於正確的位置(pivotpos)上,它無須參加後續的排序。
(2) 求解 
通過遞迴調用快速排序對左、右子區間R[low..pivotpos-1]和R[pivotpos+1..high]分別進行快速排序。
(3) 組合 
因為當“求解”步驟中的兩個遞迴調用結束時,其左、右兩個子區間已有序。對快速排序而言,“組合”步驟無須做什麼,可看做是空操作。

 1 #include <stdio.h> 2  3 int partition(int *a, int low, int high) 4 { 5     int key = a[low]; 6     while(low<high) 7     { 8         while(low<high && a[high]>key) 9             high--;10         if(a[high]<key)11             a[low] = a[high];12         while(low<high && a[low]<=key)13             low++;14         if(a[low]>key)15             a[high] = a[low];16     }17     a[low] = key;18     return low;19 }20 int quick_sort(int a[], int low, int high)21 {22     int pos;23     if(low<high)24     {25         pos = partition(a, low, high);26         quick_sort(a, low, pos-1);27         quick_sort(a, pos+1, high);28     }29 }30 31 int main()32 {33     int i;34     int arr[] = {12, 33, 25,87, 90, 77, 35, 77, 46, 29};35     quick_sort(arr,0, 9);36     for(i=0;i<10;i++)37     {38         printf("%d\t", arr[i]);39     }40     printf("\n");41     return 0;42 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.