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

#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;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值