C++快速排序的递归和非递归实现

#include<iostream>
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <stack>
using namespace std;
 
int PartSort(int* pArray, int nLeft, int nRight)
{
   
    int nKey = pArray[nLeft];
    while (nLeft < nRight)
    {
   
        while (pArray[nRight] >= nKey && nRight > nLeft)
        {
   
            nRight--;
        }
        pArray[nLeft] = pArray[nRight];
        while (pArray[nLeft] < nKey && nLeft < nRight)
        {
   
            nLeft++;
        }
        pArray[nRight]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++实现非递归快速排序通常使用栈来模拟递归过程。这是一种常见的技巧,可以避免直接的递归调用带来的栈溢出问题。以下是基本的非递归快速排序算法的步骤: 1. **分治策略**: 快速排序的核心思想是选取一个基准元素(pivot),将数组分为两部分,一部分所有元素都小于基准,另一部分所有元素都大于或等于基准。 2. **栈实现**: - 初始化一个空栈,然后压入两个指针,一个指向数组的开始,另一个指向结束。 - 当栈不为空且两个指针未相遇时,执行以下操作: - 弹出栈顶元素,取出基准元素。 - 找到基准的正确位置(小于基准的元素在左边,大于等于基准的元素在右边)。 - 将新的分割点的指针(小于基准的右边界)压入栈中。 - 将基准右侧的指针(大于等于基准的左边界)压入栈中。 3. **交换和分区**: - 在找到新分割点的过程中,如果遇到比基准小的元素,就将其与基准左边的元素交换,这样左侧的所有元素都小于基准。 - 如果遇到比基准大的元素,不做交换。 4. **递归终止条件**: - 当栈中只剩下一个元素或为空时,表示已经对当前子区间完成了排序。 5. **合并结果**: - 从栈中弹出的子区间都是排好序的,可以通过遍历栈,依次将每个子区间的有序部分合并回原始数组。 下面是简化的C++代码示例: ```cpp #include <vector> #include <stack> int partition(std::vector<int>& arr, int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; ++j) { if (arr[j] < pivot) { i++; std::swap(arr[i], arr[j]); } } std::swap(arr[i + 1], arr[high]); return i + 1; } void non_recursive_quick_sort(std::vector<int>& arr, int low, int high) { std::stack<std::pair<int, int>> s; s.push({low, high}); while (!s.empty()) { auto [left, right] = s.top(); s.pop(); if (left < right) { int pivot_pos = partition(arr, left, right); s.push({left, pivot_pos - 1}); s.push({pivot_pos + 1, right}); } } } // 示例用法 int main() { std::vector<int> vec = {9, 7, 5, 11, 12, 2, 14, 3, 10}; non_recursive_quick_sort(vec, 0, vec.size() - 1); // 输出排序后的数组 for (const auto& num : vec) { std::cout << num << " "; } return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值