快速排序的递归和非递归实现方法

快速排序的递归和非递归实现方法

/*
快速排序的两种实现方法:
1、递归实现 
2、非递归实现
*/ 
#include <iostream>
#include<stack>
using namespace std;
//以a[0]作为枢轴,将数组分开 
int partition(int a[],int left,int right)
{
	int temp=a[left];
	while(left<right)
	{
		while(left<right&&a[right]>temp)
			right--;
		a[left]=a[right];
		while(left<right&&a[left]<temp)
			left++;
		a[right]=a[left];
	}
	a[left]=temp;
	return left;
}

//递归快排 
void quicksort(int a[],int left,int right)
{
	if(left<right)
	{
		int p=partition(a,left,right);
		quicksort(a,left,p-1);
		quicksort(a,p+1,right);
	}
}

//非递归快排:用栈来存储两端的位置
void quickNonRecur(int a[],int left,int right)
{
	stack<int>s;//存储两端的位置
	if(left<right)
	{
		int pos=partition(a,left,right);//第一次切分
		if(left<pos-1)//左边至少要有两个元素,若只有一个元素,则不用排了 
		{
			s.push(left);
			s.push(pos-1); 
		 }
		 if(pos+1<right)//同理,右边也至少有两个元素。只有一个话的就自动有序了
		 {
		 	s.push(pos+1);//成对入栈 
		 	s.push(right);
		  } 
		  while(!s.empty())
		  {
		  	int r=s.top();//每次必须是成对出栈 
		  	s.pop();
		  	int l=s.top();
		  	s.pop();
		  	
		  	pos=partition(a,l,r);
		  	if(pos-1>l)//不是1,而是L
			{
			 	s.push(l);
			 	s.push(pos-1);
			}
			if(pos+1<r)
			{
				s.push(pos+1);
				s.push(r);
			}
			  
		  }
	 } 
}

void printArray(int a[],int n)
{
	int i=0;
	for(i=0;i<n;++i)
	{
		if(i==0)
			printf("%d",a[i]);
		else
			printf(" %d",a[i]);
	}
}
int main()
{
	int a[]={12,3,24,-21,32,13,4,5,2,67,10};
	int n=sizeof(a)/sizeof(a[0]);
	//quicksort(a,0,n-1);
	quickNonRecur(a,0,n-1); 
	printArray(a,n);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值