快速排序

快速排序算法合并排序算法一样,也是基于分治模式。对子数组A[p...r]快速排序的分治过程的三个步骤为:
分解:把数组A[p...r]分为A[p...q-1]与A[q+1...r]两部分,其中A[p...q-1]中的每个元素都小于等于A[q]而A[q+1...r]中的每个元素都大于等于A[q];
解决:通过递归调用快速排序,对子数组A[p...q-1]和A[q+1...r]进行排序;
合并:因为两个子数组是就地排序的,所以不需要额外的操作。

快速排序算法的伪代码:

 

  1. QUICKSORT(A, p < r) {
  2. 1 if p < r {
  3. 2 q = PARTITION(A, p, r);
  4. 3 QUICKSORT(a, p, q-1);
  5. 4 QUICKSORT(a, q+1, r);
  6. 5 }
  7. }


这个算法的关键在于数组的划分,即PARTITION:

    1. PARTITION(A, p, r) {
    2. 1 x = A[r];
    3. 2 i = p-1;
    4. 3 for j = p to r-1 {
    5. 4   if A[j] ≤ x {
    6. 5      i = i + 1;
    7. 6      exchange(A[i], A[j]);
    8. 7     }
    9. 8 }
    10. 9  exchange(A[i+1], A[r]);
    11. 10 return i+1;
    12. }

 1 #include<iostream>
 2 
 3 using std::cout;
 4 using std::endl;
 5 using std::cin;
 6 
 7 
 8 int Partition(int data[],int start,int end)
 9 {
10     if (data==NULL||start<0||end<0||end<=start)
11     {
12         throw std::exception("Invalid parameters");
13     }
14     int pnum = data[end];
15     int i = start - 1;
16 
17     for (int j = start; j < end;++j)
18     {
19         if (data[j]<=pnum)
20         {
21             ++i;
22             std::swap(data[i], data[j]);
23         }
24     }
25 
26     std::swap(data[++i], data[end]);
27 
28     return i;
29 }
30 
31 void quicksort(int data[],int start,int end)
32 {
33     if (data==NULL||end<start)
34     {
35         throw std::exception("Invalid parameters");
36     }
37     if (end==start)
38     {
39         return;
40     }
41     int q = Partition(data,start,end);
42     if (q>start)
43     {
44         quicksort(data, start, q - 1);
45     }
46     if (q<end)
47     {
48         quicksort(data, q + 1, end);
49     }
50                                                                                        
51 }
52 
53 int main()
54 {
55     int a[10] = {2,4,6,5,8,9,2,10,8,1};
56     
57 
58     quicksort(a, 0, 9);
59 
60     for (int i = 0; i < 10;++i)
61     {
62         cout << a[i] << " ";
63     }
64 
65     return 0;
66 }
View Code
原文地址:https://www.cnblogs.com/haoliuhust/p/4446403.html