最近看算法导论,看到里面的快排和以前自己一直写的快排不太一样,在分块那里的算法并不一样,下面两个版本的快排中,其中一个是指定一个元素作为比较对象的,另一个是随机指定的。
第一个是指定元素作为比较对象的
#include <iostream>
using namespace std;
int Partition(int A[],int p,int r)
{
int x=A[r],i=p-1,temp;
for(int j=p;j<r;j++)
{
if(A[j]<=x)
{
i++;
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
temp=A[i+1];
A[i+1]=A[r];
A[r]=temp;
return i+1;
}
void Quick_Sort(int A[],int low,int high)
{
if(low<high)
{
int m=Partition(A,low,high);
Quick_Sort(A,low,m-1);
Quick_Sort(A,m+1,high);
}
}
随机指定
#include <time.h>
#include <iostream>
using namespace std;
int Partition(int A[],int p,int r)
{
int x=A[r],i=p-1,j,temp;
for(j=p;j<r;j++)
{
if(A[j]<=x)
{
i++;
temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
temp=A[r];
A[r]=A[i+1];
A[i+1]=temp;
return i+1;
}
int Random_Partition(int A[],int p,int r)
{
srand((unsigned int)time(0));
int i=(rand()%(r-p+1))+p; //产生[p,r]范围的随机数
int temp=A[r];
A[r]=A[i];
A[i]=temp;
return Partition(A,p,r);
}
void Quick_Sort(int A[],int low,int high)
{
if(low<high)
{
int m=Random_Partition(A,low,high);
Quick_Sort(A,low,m-1);
Quick_Sort(A,m+1,high);
}
}
测试的主函数
#include "quicksort.h"
int main()
{
int A[50000]={0},n;
srand((unsigned int)time(0));
for(int i=0;i<50000;i++)
A[i]=rand()%89999;
clock_t star=clock(),end(0);
Quick_Sort(A,0,49999);
end=clock();
cout<<"用时 "<<double(end-star)<<"ms"<<endl;
/*
int A[10]={12,5,6554,232,2,432,11,234,69,10};
Quick_Sort(A,0,9);
for(int i=0;i<10;i++)
cout<<A[i]<<" ";
cout<<endl;
*/
return 0;
}