c++ 快速排序

 1 #include<iostream>
 2 using namespace std;
 3 
 4 void swap(int &a,int &b)
 5 {
 6     if(a==b)
 7         return;
 8     a=a+b;
 9     b=a-b;
10     a=a-b;
11 }
12 
13 int qsort(int *array,int low,int high)
14 {
15     int key=array[low];
16     cout<<"key="<<key<<endl;
17     while(low < high)
18     {
19         while(low < high && key <= array[high])
20             high--;
21         swap(array[low],array[high]);
22         
23         while(low < high && key >= array[low])
24             low++;
25         swap(array[low],array[high]);
26     }
27     cout<<"low="<<low<<endl;
28     return low;
29 }
30 
31 void quitsort(int *buf,int low,int high)//参数里的low永远都是0,high永远都是sizeof(buf)/sizeof(int)-1
32 {
33     if(low < high)
34     {
35         int pos=qsort(buf,low,high);
36 
37         //qsort(buf,low,key-1);//递归错误!
38         //qsort(buf,key+1,high);
39         quitsort(buf,low,pos-1);//前面的if(low < high)判断很重要
40         quitsort(buf,pos+1,high);
41     }
42 }
43 
44 void print(int *p,int length)
45 {
46     for(int i=0;i<length;++i)
47     {
48         cout<<p[i]<<" ";
49     }
50     cout<<endl;
51 }
52 
53 int main()
54 {
55     //int buf[10]={2,3,60,42,8,199,20,5,6,7};
56     int buf[6]={5,8,9,16,2,4};
57     cout<<"排序前:"<<endl;
58     print(buf,sizeof(buf)/sizeof(int));
59     quitsort(buf,0,sizeof(buf)/sizeof(int)-1);
60     cout<<"排序后:"<<endl;
61     print(buf,sizeof(buf)/sizeof(int));
62 }

g++ -std=c++11编译

原文地址:https://www.cnblogs.com/Hwangzhiyoung/p/8435021.html