您的位置:首页 > 产品设计 > UI/UE

算法导论 第七章:快速排序(Quicksort)

2015-07-14 19:53 585 查看
        前面我们谈论到的归并排序、堆排序的时间复杂度都是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
;
for(int i=0;i<N;i++)
a[i] = N-i;
int n=sizeof(a)/sizeof(int);
int *A=new int
;
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的逆序数组时,随机快排所以时间明显更少~

【注:如有错误,还望指正~~~】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息