改進(jìn)partition 算法代碼
#include<iostream>?
#include<algorithm>
using namespace std;?
//演示3-way-partition 給定n個數(shù)據(jù),將其按第一個數(shù)據(jù)做分區(qū)中樞
//threep返回兩個數(shù)據(jù),分別為中間段的起始和終止位置下標(biāo)?
// p中間段起始下標(biāo),r是中間段截止下標(biāo)??
void threep(int a[],int &p,int &r)
?{
? int x=a[p];?
? int k=p+1;
? while(k<=r)
? {
? if(a[k]<x)swap(a[k++],a[p++]);
? else if(a[k]>x)swap(a[k],a[r--]);
? else k++;
}
?}
?void quicksort(int a[],int left,int right)
?{
? if(left<right)
? {? int lleft=left,rright=right;
? threep(a, lleft,rright);
? quicksort(a,left,lleft-1);
? quicksort(a,rright+1,right);
}
?}
int main()
{
? int n,p,r;
? cin>>n;
? int a[n];
? for(int i=0;i<n;i++)cin>>a[i];? //5 7 5 2? 5 8
? p=0;r=n-1;
? threep(a,p,r);?
? for(int i=0;i<n;i++)cout<<a[i]<<" ";?
? cout<<"\np="<<p<<"? r="<<r;?
? // quicksort(a,p,r);
? //for(int i=0;i<n;i++)cout<<a[i]<<" ";?
? return 0;
}