欢迎光临散文网 会员登陆 & 注册

改进partition 算法代码

2023-05-26 09:52 作者:算法设计与分析张老师  | 我要投稿

#include<iostream> 

#include<algorithm>

using namespace std; 

//演示3-way-partition 给定n个数据,将其按第一个数据做分区中枢

//threep返回两个数据,分别为中间段的起始和终止位置下标 

// p中间段起始下标,r是中间段截止下标  

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;

}


改进partition 算法代码的评论 (共 条)

分享到微博请遵守国家法律