(日志,《算法导论》.7)快速排序,代码

来源:互联网 发布:wpf编程宝典c 编辑:程序博客网 时间:2024/05/20 04:48
</pre><p><pre name="code" class="cpp">/*********************************************************************************** 程序名称  :quicksort_test功能描述  : 快速排序  修改历史      :  1.日    期   : 2015/10/6作    者   : gqkly 内容       :   ************************************************************************************/  #include <iostream>  #include <time.h>  using namespace std;  typedef int ElemType;  #define N 36#define Init_A(A,n) {for(int i=0;i<n;i++)A[i]=rand()%89+10;} //#define Swap(a,b) {a=a+b;b=a-b;a=a-b;}  //存在溢出问题,所以要和另一种a,b顺序相反的方法结合使用#define Swap(a,b) {int tmp;tmp=b;b=a;a=tmp;}void Quick_Sort(ElemType *A,int p,int r);ElemType Partition(ElemType *A,int p,int r);void Print(ElemType *A,char *string);int main(){int time_start=0,time_end=0;time_start=clock();srand(NULL);ElemType A[N];Init_A(A,N);//随机初始化数组Print(A,"\n初始化后的数组:");Quick_Sort(A,0,N-1);//快速排序Print(A,"\n快速排序后的数组:");time_end=clock();cout<<"\nClock time used:"<<time_end-time_start<<endl;getchar();return 0;}void Quick_Sort(ElemType *A,int p,int r){if (p<r){int q=Partition(A,p,r);Quick_Sort(A,p,q-1);Quick_Sort(A,q+1,r);}}ElemType Partition(ElemType *A,int p,int r){ElemType x=A[r];    inti=p-1;for (int j=p;j<r;j++){if (A[j]<=x){i++;Swap(A[i],A[j]);}}i++;Swap(A[i],A[r]);return i;}void Print(ElemType *A,char *string){cout.setf(ios::right,ios::adjustfield);cout<<"\n******************************************"<<endl;cout<<string<<endl;for (int i=0;i<N;i++){if (i%6==0){cout<<endl;}cout<<A[i]<<' ';}}


运行结果:


0 0
原创粉丝点击