快速排序非递归版本

用栈记录每次要排序的左端点和右端点。

 

 1 int Partition(int a[], int f, int l) {
 2     int i = f - 1;
 3     for (int j = f; j < l; j++)
 4     {
 5         if (a[j] <= a[l]) {
 6             i++;
 7             swap(a[i], a[j]);
 8         }
 9     }
10     i++;
11     swap(a[i], a[l]);
12     return i;
13 }
14  
15 void QuickSort(int a[], int f, int l) {
16     if (f >= l)
17         return;
18     stack<int> s;
19     s.push(f);
20     s.push(l);
21 
22     while (!s.empty())
23     {
24         int right = s.top();
25         s.pop();
26         int left = s.top();
27         s.pop();
28         if (left < right)
29         {
30             int p = Partition(a, left, right);
31             // 左区间
32             s.push(left);
33             s.push(p - 1);
34             // 右区间
35             s.push(p + 1);
36             s.push(right);
37         }
38     }
39 }

 

posted @ 2018-10-19 15:47  FlyingWarrior  阅读(256)  评论(0编辑  收藏  举报