照例算法复习,顺便记录一下快排,以后忘记了不用翻书吧
思想是将一个数组啊a[p:r]以元素a[p]为基础分为a[p:q-1],a[q],a[q+1:r]三段,前半段全部比中间小,后半段全部比中间大,递归排序后,就直接排序好了!
#include<iostream>
using namespace std;
int Partition(int a[],int p,int r){ //返回该段中间的那个数
int i=p,j=r+1;
int x=a[p];
while(true){
while(a[++i]<x && i<r) ;
while(a[--j]>x ) ;
if(i>=j) break;
swap(a[i],a[j]);
}
a[p] = a[j];
a[j] = x;
return j;
}
void QuickSort(int a[],int p,int r){
if(p<r){
int q=Partition(a,p,r);
QuickSort(a,p,q-1);
QuickSort(a,q+1,r);
}
}
int main()
{
int a[5]={1,4,23,5,3};
QuickSort(a,0,4);
for(int x=0;x<=4;x++)
{
cout<<a[x]<<" ";
}
}