You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++递归实现快速排序程序执行完成无输出问题求助

问题根因

你的程序没有执行到最终的cout输出,是因为快排逻辑存在数组越界、无限递归问题,程序在排序过程中直接崩溃,和cout本身无关,具体错误点如下:

  • partition函数的指针遍历逻辑没有做边界限制,当pivot为当前区间最小值时,左指针会持续递增超出数组合法范围,触发非法内存访问
  • 递归区间参数传递错误,返回的pivot位置已经是排序完成的正确位置,不需要再参与后续排序,左半段递归应该传入new_limit - 1而非new_limit,否则会触发无限递归栈溢出
  • 用加减法实现同地址元素交换时会破坏原始值,不如临时变量交换逻辑稳妥
  • a[0]设置哨兵的逻辑和当前partition逻辑不匹配,反而会干扰边界判断

修复后代码

#include <iostream>
using namespace std;

int partition(int a[], int low, int high)
{
    int pivot = a[high];
    int x = low - 1;
    for (int j = low; j < high; j++)
    {
        if (a[j] <= pivot)
        {
            x++;
            int temp = a[x];
            a[x] = a[j];
            a[j] = temp;
        }
    }
    int temp = a[x + 1];
    a[x + 1] = a[high];
    a[high] = temp;
    return x + 1;
}

void quickSort(int a[], int low, int high)
{
    if (low < high)
    {
        int new_limit = partition(a, low, high);
        quickSort(a, low, new_limit - 1);
        quickSort(a, new_limit + 1, high);
    }
}

int main()
{
    int n;
    int a[1001];
    cin >> n;
    for (int i = 1; i <= n; ++i)
    {
        cin >> a[i];
    }

    quickSort(a, 1, n);

    for (int i = 1; i <= n; ++i)
    {
        cout << a[i] << " ";
    }

    return 0;
}

验证说明

输入你提供的测试用例:

7
8 7 14 6 98 5 4

输出结果为:

4 5 6 7 8 14 98 

内容的提问来源于stack exchange,提问作者user14812745

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:45:04