快速排序
基本思想:
将首元素x作为划分标准,将输入数组A划分为不超过x的元素构成数组A1,将大于x的元素构成的数组作为A2,从左到右存放在数组A的位置。
递归的对子问题A1,A2进行排序,知道子问题规模为1时停止。
过程:
代码:
int swap(vector<int> &a,int begin,int end,int x){
int i=begin+1;
int j= end;
while(true){
while(a[i]<x) i++;
while(a[j]>x) j--;
if(i<j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}else {
return j;
}
}
}
int QuickSort(vector<int> &a,int begin,int end){
if(begin<end){
int x = a[begin];//x为首元素
int partition = swap(a,begin,end,x);
a[begin] = a[partition];
a[partition] = x;
QuickSort(a,begin,partition-1);
QuickSort(a,partition+1,end);
}
return 0;
}