照例算法複習,順便記錄一下快排,以後忘記了不用翻書吧
思想是將一個數組啊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]<<" ";
}
}