快排非递归实现
来源:互联网 发布:老外在中国 知乎 编辑:程序博客网 时间:2024/05/16 04:47
#include <iostream>#include <cstdlib>using namespace std;#define MAX 10int partition(int Array[], int low, int high){int pivot = Array[high];while (low<high){while (Array[low]<pivot && low<high){low++;}if (low<high){Array[high]=Array[low];high--;}while (Array[high]>pivot && low<high){high--;}if (low<high){Array[low]=Array[high];low++;}}Array[low]=pivot;return low;}void QuickSort(int Array[], int low, int high){int *stack = new int[high-low+1];int top=0;int mid;stack[top]=low;top++;stack[top]=high;top++;while(top!=0){top--;high=stack[top];top--;low=stack[top];if (low<high){mid=partition(Array, low, high);if ((mid-low) > (high-mid)){stack[top]=low;top++;stack[top]=mid-1;top++;if (high-mid>0){stack[top]=mid+1;top++;stack[top]=high;top++;}}else{stack[top]=mid+1;top++;stack[top]=high;top++;if (mid-low>0){stack[top]=low;top++;stack[top]=mid-1;top++;}}}}for (int i=0;i<10;i++){cout<<Array[i]<<" ";}cout<<endl;delete stack;}int main(int argc, char* argv[]){int a[MAX];for (int i=0; i<MAX;i++){a[i]=rand()%100;cout<<a[i]<<" ";}cout<<endl;QuickSort(a,0,MAX-1);return 0;}