正文

快速排序(分治法)2006-11-22 17:22:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/jixian/20630.html

分享到:

//快速排序法

#include<iostream>
#include<cstdlib>
using namespace std;

int part(int s[],int p,int r)   //把大于s[p]的数放一边,小于它的数放一边
{
 int x = s[p];
 int i = p+1;
 int j = r;
 while(true)
 {
  while(s[i] < x && i<=r)  i++;
  while(s[j] > x && j>=1)  j--;
  if(i >=j)
   break;
  int temp = s[i];
  s[i] = s[j];
  s[j] = temp;
 }
 s[p] = s[j];
 s[j] = x;
 return j;
}


void quicksort(int s[],int p,int r)
{
 if(p < r)
 {
  int q = part(s,p,r);
  quicksort(s, p,q-1);
  quicksort(s,q+1,r);
 }
}

int main()
{
 int s[] = {1,5,3,8,4,10,5};
 int p = 0;
 int r= sizeof s/sizeof *s -1;
 cout<<"排序前: "<<endl;
 for(int i=0;i<=r;i++)
  cout<<s[i]<<"  ";
 cout<<endl;
 quicksort(s,p,r);
 cout<<"排序后: "<<endl;
 for(i=0;i<=r;i++)
  cout<<s[i]<<"  ";
 cout<<endl;
}

阅读(4403) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册