C++快速排序

來源:互聯網
上載者:User
 1 // 快速排序:begin
2 // 快速排序在平均情況下的時間複雜性是O(nlogn),快速排序時不穩定的排序
3
4 // 方法1:
5 template<class T>
6 void quick_sort1(T *a, int left, int right)
7 {
8 if (left < right) // 數組元素至少有2個才進行排序
9 {
10 int p = partition(a, left, right);
11 quick_sort1(a, left, p - 1);
12 quick_sort1(a, p + 1, right);
13 }
14 }
15
16 template<class T>
17 int partition(T *a, int left, int right)
18 {
19 int l = left, r = right;
20 T pivot = a[left];
21 while (l < r)
22 {
23 while (a[l] < pivot) ++l;
24 while (a[r] > pivot) --r;
25 swap(a[l], a[r]);
26 }
27 swap(a[l], a[r]); // 當i>=j時,上面while迴圈會多swap操作一次,所以必須撤銷最後一次操作
28 swap(a[r], pivot);
29
30 return r;
31 }
32
33 //==================================
34 // 方法2:
35 template<class T>
36 void quick_sort2(T *a, int left, int right)
37 {
38 if(left >= right)
39 return;
40
41 int l = left, r = right;
42 T pivot = a[left];
43 while(l != r)
44 {
45 while(l < r && a[r] >= pivot) r--;
46 a[l] = a[r];
47 while(l < r && a[l] <= pivot) l++;
48 a[r] = a[l];
49 }
50 a[l] = pivot;
51
52 quick_sort2(a, left, l - 1);
53 quick_sort2(a, l + 1, right);
54 }
55 // 快速排序:end

 

測試代碼如下:

 1 int main()
2 {
3 // 測試快速排序
4 int test1[7] = {7, 6, 5, 4, 3, 2 ,1};
5 // char test1[7] = {'e', 'x', 'a', 'm', 'p', 'l', 'e'};
6 //quick_sort1(test1, 0, 6);
7 quick_sort2(test1, 0, 6);
8 cout << "After QuickSort:"<<endl;
9 for(int i = 0; i < 7; ++i)
10 cout << test1[i] << "";
11 cout << endl;
12
13 return 0;
14 }

 

聯繫我們

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