现在的位置: 首页 > 综合 > 正文

快速排序(分治法)

2013年06月27日 ⁄ 综合 ⁄ 共 670字 ⁄ 字号 评论关闭
 1 //快速排序法
 2 
 3 #include<iostream>
 4 #include<cstdlib>
 5 using namespace std;
 6 
 7 int part(int s[],int p,int r)   //把大于s[p]的数放一边,小于它的数放一边
 8 {
 9  int x = s[p];
10  int i = p+1;
11  int j = r;
12  while(true)
13  {
14   while(s[i] < x && i<=r)  i++;
15   while(s[j] > x && j>=1)  j--;
16   if(i >=j)
17    break;
18   int temp = s[i];
19   s[i] = s[j];
20   s[j] = temp;
21  }
22  s[p] = s[j];
23  s[j] = x;
24  return j;
25 }
26 
27 
28 void quicksort(int s[],int p,int r)
29 {
30  if(p < r)
31  {
32   int q = part(s,p,r);
33   quicksort(s, p,q-1);
34   quicksort(s,q+1,r);
35  }
36 }
37 
38 int main()
39 {
40  int s[] = {1,5,3,8,4,10,5};
41  int p = 0;
42  int r= sizeof s/sizeof *s -1;
43  cout<<"排序前: "<<endl;
44  for(int i=0;i<=r;i++)
45   cout<<s[i]<<"  ";
46  cout<<endl;
47  quicksort(s,p,r);
48  cout<<"排序后: "<<endl;
49  for(i=0;i<=r;i++)
50   cout<<s[i]<<"  ";
51  cout<<endl;
52 }

 

抱歉!评论已关闭.