快速排序的演算法導論劃分形式和hoare劃分

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   art   ar   div   

  1. hoare劃分

 1 int hoare_partition(int a[], int begin, int end) 2 {     3     int pivot = a[begin]; 4     int ini = begin;  5     int ter = end; 6     while (ini < ter) 7     { 8         while (a[ini] <= pivot && ini <end) 9             ++ini;10         while (a[ter] >= pivot && ter>begin)11             --ter;12         if (ini<ter)13             swap(a[ini], a[ter]);14         15     }16     swap(a[ter], a[begin]);17     return ter;18     19 }20 void quick_sort(int a[], int begin, int end)21 {22         if (begin < end)23         {24             int div = hoare_partition(a, begin, end);25             cout << div << endl;26             quick_sort(a, begin, div);27             28             quick_sort(a, div+1, end);29         }30         31 }
  1.  1
    演算法導論的劃分形式
    int partition(int a[], int begin, int end) 2 { 3 int pivot = a[begin]; 4 int cur = begin + 1; 5 int divid_location = begin; 6 for (; cur <= end; ++cur) 7 { 8 if (a[cur] < pivot) 9 {10 ++divid_location;11 int temp = a[divid_location];12 a[divid_location] = a[cur];13 a[cur] = temp;14 }15 }16 a[begin] = a[divid_location];17 a[divid_location] = pivot;18 return divid_location;19 }20 void quick_sort(int a[], int begin,int end)21 {22 if (end-begin > min_size)23 {24 int div = partition(a, begin, end);25 quick_sort(a, begin, div);26 int div_plus_1 = div + 1;27 quick_sort(a,div_plus_1, end);28 }29 insert_sort(a, begin, end);30 }

    區別在哪呢,區別在於hoare劃分將區間分為兩部分,而主元可能位於兩個區間的任何一個,而算導的劃分將其劃為3部分。

    median-of-3改進等比較簡單,不再贅述。

 

    關於快速排序的工業級實現,參見STL 源碼剖析當中的講解,我們會發現,和我們寫的版本基本一致,當然為了保證遞迴不是很深,會進行最佳化,比如只對每次劃分較短的一側進行遞迴,另一個尾遞迴最佳化。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.