前面我們談論到的歸併排序、堆排序的時間複雜度都是O(nlgn),快速排序的時間複雜度也爲Θ(nlgn)。但在實際中,快排序往往要優於前兩種,因爲隱藏在Θ(nlgn)中的常數因子非常小。此外,快速排序是一種就地(in place)排序,在虛擬內存、硬件緩存等環境中非常有效。
快速排序的基本原理爲分治:
1)將數組A[p...r]劃分成兩個子數組A[p...q-1]和A[q+1...r],滿足A[p...q-1]中的元素 ≤ A[q]; A[q+1...r]中的元素 ≥ A[q]. (q的位置通過調用PARTITION程序在線性時間內計算)
2)遞歸排序兩子數組A[p...q-1]和A[q+1...r]
3)將結果合併
固定劃分
劃分僞代碼如下:
快排僞代碼如下:
性能分析:
最壞情況(worst-case):
當輸入已經排好序,那麼劃分時,有個子數組中將沒有元素,因此有:
T(n) = T(0)+T(n-1)+Θ(n) = Θ(n²)
最好情況(best-case):
從中間劃分,則:
T(n) = 2T(n/2)+Θ(n) = Θ(nlgn)
隨機劃分
由於固定劃分對輸入有限制,因此我們採用隨機劃分,隨機選取劃分主元,僞代碼如下:
性能分析:
所以當a足夠大,滿足an/4 >Θ(n)時 ,上式成立。
完整代碼如下:
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
void Print(int *a)
{
int n=a[0];
for(int i=1;i<=n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int *Transform(int *a,int n)
{
int *A=new int[n+1];
A[0]=n;
for(int i=0;i<n;i++)
A[i+1]=a[i];
return A;
}
void swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int Partition(int *A,int low,int high)
{
int i=low-1;
int t=A[high];
for(int j=low;j<=high-1;j++)
if(A[j]<t)
{
i=i+1;
swap(A[i],A[j]);
}
swap(A[i+1],A[high]);
return i+1;
}
void QSort(int *A,int low,int high)
{
if(low<high)
{
int q=Partition(A,low,high);
QSort(A,low,q-1);
QSort(A,q+1,high);
}
}
void QuickSort(int *A)
{
int n=A[0];
QSort(A,1,n);
}
int Random_Partition(int *A,int low,int high)
{
srand((unsigned)time(NULL));
int i=rand()%(high-low+1)+low; //random number [low,high];
swap(A[i],A[high]);
return Partition(A,low,high);
}
void Random_Qsort(int *A,int low,int high)
{
if(low<high)
{
int q=Random_Partition(A,low,high);
Random_Qsort(A,low,q-1);
Random_Qsort(A,q+1,high);
}
}
void Random_QuickSort(int *A)
{
int n=A[0];
Random_Qsort(A,1,n);
}
int main()
{
//int a[]={2,8,7,1,3,5,6,4};
int N;
cout<<"Please input the size N:";
cin>>N;
int a[N];
for(int i=0;i<N;i++)
a[i] = N-i;
int n=sizeof(a)/sizeof(int);
int *A=new int[n];
A=Transform(a,n); //a[0..n-1]->A[1..n] ;A[0]=a.length
cout<<"----------The general Quicksort-------------"<<endl;
int s1=clock();
QuickSort(A);
int e1=clock();
//Print(A);
cout<<"Taking time:"<<(float)e1-s1<<endl;
cout<<"-----------The random Quicksort--------------"<<endl;
int s2=clock();
Random_QuickSort(A);
int e2=clock();
//Print(A);
cout<<"Taking time:"<<(float)e2-s2<<endl;
}
運行結果如下:
當輸入大小爲10000的逆序數組時,隨機快排所以時間明顯更少~
【注:如有錯誤,還望指正~~~】