快速排序的非递归写法

来源:互联网 发布:淘宝怎么异地发货 编辑:程序博客网 时间:2024/06/03 11:18
#include<iostream>#include<stack>using namespace std;struct node{int left;int right;};void Swap(int *x, int *y){int tmp = *x;*x = *y;*y = tmp;}int Median(int *a, int left, int right){int center = (left + right) / 2;if (a[left] > a[center])Swap(&a[left], &a[center]);if (a[left] > a[right])Swap(&a[left], &a[right]);if (a[center] > a[right])Swap(&a[center], &a[right]);Swap(&a[center], &a[right - 1]);return a[right - 1];}void partition(int *a, int left, int right, stack<node>* LR){int pivot = Median(a, left, right);int l = left;int r = right - 1;while (l < r){while (a[++l] < pivot);while (a[--r] > pivot);if (l < r)Swap(&a[l], &a[r]);elsebreak;}Swap(&a[l], &a[right - 1]);if (l < right && r > left){node lr;lr.left = left;lr.right = l - 1;LR->push(lr);lr.left = l + 1;lr.right = right;LR->push(lr);}}void QuickSort(int *a, int left, int right, stack<node>* LR){if (left == right)return;node lr;lr.left = left;lr.right = right;LR->push(lr);while (!LR->empty()){lr = LR->top();int l = lr.left;int r = lr.right;LR->pop();partition(a, l, r, LR);}}int main(){int a[] = { 1, 7, 9, 3, 2, 5, 6, 9, 0, 4, 2, 7, 9, 10, 1 };stack<node> *LR = new stack<node>();QuickSort(a, 0, 14, LR);for (int i = 0; i < 15; i++)cout << a[i] << " ";}

0 0
原创粉丝点击