快排的递归与非递归实现


/*----------------------------------------------------
 *快排的优化函数
 *随机一个位置(begin~end),该元素作为基准元素
 *----------------------------------------------------*/
template <typename ElementType>
void Random(ElementType x[], int begin, int end)
{
	srand((unsigned)time(NULL));
	int pos = rand() % (end - begin + 1) + begin;
	swap(x[pos], x[begin]);
}

/*-------------------------------------------------------
 *重排x[begin],...,x[end], 定好基准的位置
 *
 *前置条件:已经为ElementType定义了<和==运算符,
 *          first <= last,
 *后置条件:子列表中元素被重排并返回pos使得x[first],
 *          ...,x[pos-1] <= x[pos] < x[pos+1],...,x[end]
 *--------------------------------------------------------*/
template <typename ElementType>
int Partition(ElementType x[], int begin, int end)
{
    Random(x, begin, end);
    ElementType pivot = x[begin];       //基准元素
    int left = begin;
    int right = end;
    
    while(left < right)
    {
        while(left < right && x[right] >= pivot)         //从右往左查找<=基准的元素
        {
            right--;
        }
        //从左往右查找>基准的元素
        while(left < right && x[left] <= pivot)
        {
            left++;
        }
        if(left < right)//若尚未碰头则交换元素
        {
            swap(x[left], x[right]);
        }
    }
    
    swap(x[begin], x[right]);
    return right;
}

/*-------------------------------------------------------
 *排序x[begin],...,x[end], 使之升序排列
 *
 *前置条件:已经为ElementType定义了<和==运算符,
 *          first <= last,
 *后置条件:x[first],...,x[end]排好序        
 *--------------------------------------------------------*/
template <typename ElementType>
void quickSort(ElementType x[], int begin, int end)//递归实现
{
    int pos;
    if(begin < end)
    {
        pos = Partition(x, begin, end);
        quickSort(x, begin, pos - 1);
        quickSort(x, pos + 1, end);
    }
}
template <typename ElementType>
void quickSortNoRecursive(ElementType x[], int begin, int end)//非递归实现
{
	stack<int> s;//用于保存每一次partition后的左右子序列的begin和end
	int left = begin;
	int right = end;
	s.push(right);//注意left和right的进栈顺序
	s.push(left);
	while(!s.empty())
	{
		left = s.top();
		s.pop();
		right = s.top();
		s.pop();
		if(left < right)
		{
			int mid = Partition(x, left, right);
			if(mid - 1 > left)
			{
				s.push(mid - 1);
				s.push(left);
			}
			if(mid + 1 < right)
			{
				s.push(right);
				s.push(mid + 1);
			}
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值