经典算法 之 快速排序 QuickSort

好长时间没温习过算法了,简单的快排都不知道怎么写了,好在抽出时间再温习一下...

1、快速排序最坏情况运行时间为O(n2),平均情况运行时间为O(nlgn)

2、快速排序和合并排序一样,也是基于分治模式的。

3、快速排序算法的关键是Partition 过程,它对子数组A[p..r] 进行了重排:

Partition(A,p,r)

{

x←A[r]

i←p-1

for j←p to r-1

  do if A[j]≤ x

  then i←i+1

    exchange A[i]↔A[j]

exchange A[i+1]↔A[r]

return i+1

}

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int Partition(int *a,int left,int right);
 5 void QSort(int *a,int left,int right);
 6 
 7 int main()
 8 {
 9     int n,left,right,middle;
10     int a[100];
11     while (1)
12     {
13         cin>>n;
14         for(int i=0;i<n;i++)
15         {
16             cin>>a[i];
17         }
18         right=n;
19         QSort(a,0,n-1);
20         for(int i=0;i<n;i++)
21         {
22             cout<<a[i]<<" "<<endl;
23         }
24     }
25     return 0;
26 }
27 
28 int Partition(int a[],int left,int right)
29 {
30     int x=right,i=left-1;
31     for(int j=left;j<=right-1;j++)
32     {
33         if(a[j]<a[x])
34         {
35             i++;
36             swap(a[j],a[i]);
37         }
38     }
39     swap(a[i+1],a[x]);
40     return i+1;
41 }
42 void QSort(int a[],int left,int right)
43 {
44     int pivotpos;
45     if(left<right)
46     {
47         pivotpos=Partition(a,left,right);
48         QSort(a,left,pivotpos-1);
49         QSort(a,pivotpos+1,right);
50     }
51 }
View Code
原文地址:https://www.cnblogs.com/ouweiqideblog/p/3245418.html