不使用遞迴實現的快速排序
阿新 • • 發佈:2019-02-14
#include<iostream> #include<queue> using namespace std; void QSort(int* array, int count) { queue<int> First; queue<int> Last; First.push(0); Last.push(count - 1); while(!First.empty()) { int first = First.front(); int last = Last.front(); First.pop(); Last.pop(); int ctrl = array[first]; int curr = 0; int i = first, j = last; while(i < j) { if(curr == 0) { while(array[j] > ctrl && j != i) j--; array[i] = array[j]; curr = 1; } else { while(array[i] <= ctrl && j != i) i++; array[j] = array[i]; curr = 0; } } array[i] = ctrl; if(first < i - 1) { First.push(first); Last.push(i - 1); } if(last > i + 1) { First.push(i + 1); Last.push(last); } } } int main() { int test[10] = { 4,1,7,9,3,2,6,5,0,8 }; QSort(test, 10); for(int i = 0; i < 10; i++) cout << test[i] << " "; cout << endl; return 0; }