实现快排最优版本算法上机报告

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

算法导论第二次上机报告

班级:1403018 姓名:张可心学号:14030188030

(一)题目一

一、问题

This project requires you to implement an optimized version of quicksort, and compare the performances of the following combinations:

(1)Cutoff values from 0 to 50;

(2)Take pivot to be the 1st element, random, median of random three, and

median of random five.

The tests must be done on the following three kinds of inputs:

(1)sorted input;

(2)reverse-ordered input;

(3)random input.

The size of input can be taken from 1000 to 10000. The run times must be plotted with respect to the sizes to illustrate the difference. (figure out using excel, matlab in the Report)

二、问题分析

实现快排的最优版本,分别选取第一个数,随机数,三个随机数的中位数,

五个随机数的中位数为基数,设置顺序,随机,逆序三种形式,用_qsort(int

a[],int p,int r,int number)和Partition(int a[],int p,int r,int number)俩函数进行排序。

三、算法伪代码

void _qsort(a, p, r, number)

if p

q=Partition(a,p,r,number)

_qsort(a,p,q-1,number)

_qsort(a,q+1,r,number)

int Partition(int a[],int p,int r,int number)

{

int x,temp;

if(number==1)

temp=p;

}

else if(number==2)

{

temp=rand()%(r-p+1)+p;

}

else if(number==3)

{

int b[5];

b[1]=rand()%(r-p+1)+p; b[2]=rand()%(r-p+1)+p; b[3]=rand()%(r-p+1)+p; sort(b+1,b+4);

temp=b[2];

}

else if(number==4)

{

int b[10];

b[1]=rand()%(r-p+1)+p; b[2]=rand()%(r-p+1)+p; b[3]=rand()%(r-p+1)+p; b[4]=rand()%(r-p+1)+p; b[5]=rand()%(r-p+1)+p; sort(b+1,b+6);

temp=b[3];

}

else{

temp=p;

}

x=a[temp];

swap(a[temp],a[p]);

int i=r+1;

for(int j=r;j>p;j--)

{

if(a[j]>=x)

i--;

swap(a[i],a[j]);

}

}

swap(a[i-1],a[p]);

return i-1;

}

int main()

{

int n,a[200000];

cout<<"测试数据:";

cin>>n;

for(int i=1;i<=n;i++)

a[i]=random(51);

cout<<"序列的顺序(1顺序;2随机;3逆序):";

int s;

cin>>s;

if(s==3)

sort(a+1,a+1+n,greater());//对生成数进行排列

else if(s==1)

sort(a+1,a+1+n);

else if(s==2){

}

else{

}

cout<<"确定基数:1,第一个数;2,随机数;3,3个随机数的中位数;4,5个随机数的中位数:";

int number;

cin>>number;

clock_t start,end;//计时

start=clock();

_qsort(a,1,n,number);

end=clock();

cout<<"用时:"<

for(int i=1;i<=n;i++)

{

cout<

}

return 0;

}

四、算法分析

对数据进行快排,通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

五、测试结果

1以第一个数为基数的排序时间,单位ms.

2以随机数为基数的排序时间,单位ms

相关文档
最新文档