您的位置:首页 >C++快排算法递归与非递归实现方法
发布于2026-01-18 阅读(0)
扫一扫,手机访问
快速排序基于分治思想,通过基准元素划分数组并递归或迭代排序子区间;C++中可递归实现(简洁直观)或非递归用栈模拟(避免栈溢出),核心为partition函数;实际推荐使用std::sort。

快速排序是一种高效的排序算法,基于分治思想,通过选择一个基准元素将数组划分为两部分,使得左边元素小于等于基准,右边大于等于基准,然后递归或迭代处理左右子区间。C++中可以使用递归和非递归两种方式实现快排。
递归版本是快排最直观的写法。核心在于分区(partition)操作和递归调用。
步骤如下:
#include <iostream> #include <vector> using namespace std;int partition(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++; swap(arr[i], arr[j]); } } swap(arr[i + 1], arr[high]); return i + 1;}
void quickSortRecursive(vector<int>& arr, int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSortRecursive(arr, low, pi - 1); quickSortRecursive(arr, pi + 1, high); } }
非递归版本使用栈模拟函数调用过程,避免深层递归带来的栈溢出风险。
思路:
#include <stack>void quickSortIterative(vector<int>& arr, int low, int high) { stack<pair<int, int>> stk; stk.push({low, high});
while (!stk.empty()) { auto [l, h] = stk.top(); stk.pop(); if (l < h) { int pi = partition(arr, l, h); stk.push({l, pi - 1}); stk.push({pi + 1, h}); } }}
下面是一个完整的测试程序,验证两种实现的效果。
int main() {
vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
cout << "原数组: ";
for (int x : arr) cout << x << " ";
cout << endl;
// 使用递归快排
quickSortRecursive(arr, 0, arr.size() - 1);
cout << "递归排序后: ";
for (int x : arr) cout << x << " ";
cout << endl;
// 再次打乱用于非递归测试
arr = {64, 34, 25, 12, 22, 11, 90};
quickSortIterative(arr, 0, arr.size() - 1);
cout << "非递归排序后: ";
for (int x : arr) cout << x << " ";
cout << endl;
return 0;}
基本上就这些。递归写法简洁易懂,适合一般场景;非递归更稳定,适合大数据量或栈空间受限环境。关键在于正确实现 partition 函数,并注意边界条件。实际开发中也可以直接使用 std::sort,它内部结合了快排、堆排和插入排序(Introsort),性能更优且安全。
上一篇:搜狗浏览器阅读模式怎么开启?
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9