非递归快排

防鄙视系列

 

 1 #include<iostream>
 2 #include<deque>
 3 #include<utility>
 4 
 5 using namespace std;
 6 
 7 void norecursion_QuickSort(int*,int);
 8 int partition(int*,int,int);
 9 int main()
10 {
11     int buf[]={112,332,1,200,123,-1,23214};
12     norecursion_QuickSort(buf,sizeof(buf)/4);
13     int m;
14     return 0;
15 }
16 
17 void norecursion_QuickSort(int*buf,int amount)
18 {
19     
20     typedef pair<int,int> range;
21     deque<range>* pd=new deque<range>();
22     int middle=partition(buf,0,amount-1);
23     range lrg(0,middle-1),rrg(middle+1,amount-1);
24     pd->push_back(lrg);
25     pd->push_back(rrg);
26 
27     while(!pd->empty())
28     {
29         range rg=pd->front();
30             pd->pop_front();
31         if(rg.first<rg.second)
32         {
33             int mid=partition(buf,rg.first,rg.second);
34             pd->push_back(range(rg.first,mid-1));
35             pd->push_back(range(mid+1,rg.second));
36 
37         }
38     }
39 
40     
41 }
42 
43 int partition(int*buf,int p,int q)
44 {
45     int key=buf[q];
46     int j=p-1;
47 
48     for(int i=p;i<q;i++)
49     {
50         if(buf[i]<=key)
51             std::swap(buf[++j],buf[i]);
52     }
53     std::swap(buf[++j],buf[q]);
54     return j;
55 }

 

 

 

posted @ 2013-09-10 20:31  cavehubiao  阅读(245)  评论(0编辑  收藏  举报