不得不说,手写的快排真的好菜。(即使开了随机数...)
快速排序
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; inline int read(); const int Maxn = 100010 ; namespace iNx{ int n; int q[Maxn]; void exchange(int a,int b){ int t=q[a]; q[a]=q[b]; q[b]=t; } void quicksort(int left,int right){ if(left>=right) return ; exchange(left,(rand()%(right-left+1))+left); int key=q[left],i=left,j=right; while(i<j){ while(q[j]>=key&&i<j) j--; if(j>i) q[i++]=q[j]; while(q[i]<=key&&i<j) i++; if(i<j) q[j--]=q[i]; } q[i]=key; quicksort(left,i-1); quicksort(i+1,right); } int main(){ n=read(); int i; for(i=1;i<=n;i++) q[i]=read(); quicksort(1,n); for(i=1;i<=n;i++) printf("%d ",q[i]); puts(""); return 0; } } int main(){ iNx::main(); return 0; } inline int read(){ int kk=0,ff=1; char c=getchar(); while(c<'0'||c>'9'){ if(c=='-') ff=-1; c=getchar(); } while(c>='0'&&c<='9') kk=kk*10+c-'0',c=getchar(); return kk*ff; }
归并排序
#include<iostream> #include<cstdio> #include<cstring> using namespace std; inline int read(); const int Maxn = 100010 ; namespace iNx{ int n,q[Maxn],t[Maxn]; void mergesort(int left,int right){ if(left>=right) return ; int mid=(left+right)>>1; mergesort(left,mid); mergesort(mid+1,right); int i=left,j=mid+1,k=left; while(i<=mid&&j<=right){ if(q[i]<=q[j]) t[k++]=q[i++]; else t[k++]=q[j++]; } while(i<=mid) t[k++]=q[i++]; while(j<=right) t[k++]=q[j++]; for(i=left;i<=right;i++) q[i]=t[i]; } int main(){ n=read(); int i; for(i=1;i<=n;i++) q[i]=read(); mergesort(1,n); for(i=1;i<=n;i++) printf("%d ",q[i]); puts(""); } } int main(){ iNx::main(); return 0; } inline int read(){ int kk=0,ff=1; char c=getchar(); while(c<'0'||c>'9'){ if(c=='-') ff=-1; c=getchar(); } while(c>='0'&&c<='9') kk=kk*10+c-'0',c=getchar(); return kk*ff; }
可以到洛谷上测试:P1177 【模板】快速排序
附上两种代码测评结果(此题时间限制3s):
快速排序:
归并排序:
(天天进步一点点hhh。)