不用递归,使用栈实现快速排序(非常好理解)

来源:互联网 发布:源计划亚索多少钱淘宝 编辑:程序博客网 时间:2024/06/05 23:01
#include <stack>#include <iostream>using namespace std;void swap(int &a,int &b){int temp=a;a=b;b=temp;}int partition(int arr[],int startIndex,int endIndex){int pivot=arr[startIndex];     //枢轴int tooBigIndex=startIndex,tooSmallIndex=endIndex;while(tooBigIndex<=tooSmallIndex){while(tooBigIndex<=endIndex && arr[tooBigIndex]<=pivot)tooBigIndex++;while(arr[tooSmallIndex]>pivot)  //tooSmallIndex不可能小于startIndextooSmallIndex--;             //因为如果达到startIndex,将会有                                     //arr[tooSmallIndex]=pivotif(tooBigIndex<tooSmallIndex)    //说明tooSmallIndex对应的值小于pivot,tooBigIndex对应的值大于pivotswap(arr[tooBigIndex],arr[tooSmallIndex]);}swap(arr[startIndex],arr[tooSmallIndex]);   //最后交换pivotreturn tooSmallIndex;}void qsort(int arr[],int low,int high){int startIndex,endIndex,pivotIndex;pair<int,int> apair;apair.first=low;apair.second=high;stack<pair<int,int>> s;s.push(apair);while(!s.empty()){apair=s.top(); s.pop();startIndex=apair.first;endIndex=apair.second;pivotIndex=partition(arr,startIndex,endIndex);if(startIndex<pivotIndex-1)  //the left have more than 1 element{apair.first=startIndex;apair.second=pivotIndex-1;s.push(apair);}if(endIndex>pivotIndex+1)   //the right have more than 1 element{apair.first=pivotIndex+1;apair.second=endIndex;s.push(apair);}}}int main(){int arr[]={5,4,6,3,1,-5,34,10,8,2};qsort(arr,0,9);for(int i=0;i<10;i++)cout<<arr[i]<<" ";cout<<endl;return 0;}

0 0
原创粉丝点击