登 录
自己写的快速排序模板。:-)。
第一种是常规形式,第二种加入了随机化数。
#include "time.h" #include <algorithm> #include <iostream> using namespace std; const int max_n=300; void quick_sort(int a[],int first,int last) { int left=first,right=last; int temp=a[first]; while(left<right) { while(left<right&&a[right]>=temp) right--; a[left]=a[right]; while(left<right&&a[left]<temp) left++; a[right]=a[left]; } a[left]=temp;//此时left=right if(left-1>first) quick_sort(a,first,left-1); if(right+1<last) quick_sort(a,right+1,last); } void quick_sort2(int a[],int first,int last) { int left=first,right=last; int temp=a[first+rand()%(last-first+1)]; while(1) { while(a[left]<temp) left++; while(a[right]>=temp) right--; if(left<right) { int temp2=a[left]; a[left]=a[right]; a[right]=temp2; } else break; } //此时left-right=1 if(left-1>first) quick_sort2(a,first,left-1); if(right+1<last) quick_sort2(a,right+1,last); } int main() { int pos[max_n],pos2[max_n],pos3[max_n]; srand((unsigned)time(NULL)); for(int i=0;i<max_n;i++) { pos[i]=pos2[i]=pos3[i]=rand(); } quick_sort(pos,0,max_n-1); quick_sort(pos2,0,max_n-1); sort(pos3,pos3+max_n); for(int i=0;i<max_n;i++) { printf("%d %d %d/n",pos[i],pos2[i],pos3[i]); } return 0; }
抱歉!评论已关闭.