#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不可能小于startIndex
tooSmallIndex--; //因为如果达到startIndex,将会有
//arr[tooSmallIndex]=pivot
if(tooBigIndex<tooSmallIndex) //说明tooSmallIndex对应的值小于pivot,tooBigIndex对应的值大于pivot
swap(arr[tooBigIndex],arr[tooSmallIndex]);
}
swap(arr[startIndex],arr[tooSmallIndex]); //最后交换pivot
return 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;
}
不用递归,使用栈实现快速排序(非常好理解)
最新推荐文章于 2023-06-11 23:26:34 发布