快速排序
基本思想:
将首元素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;
}
测试:
int main(){
vector<int> b = {43,13,543,765,234,8,35,54,88,45,1,3,0,4,12,34};
for(int i=0;i<b.size();i++){
cout<<b[i]<<" ";
}
cout<<endl;
QuickSort(b,0,b.size()-1);
cout<<"快速排序结果";
for(int i=0;i<b.size();i++){
cout<<b[i]<<" ";
}
return 0;
}