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

为何我编写的quicksort(快速排序)程序没有输出?

问题分析与修复

你的代码出现无限递归,导致程序栈溢出直接崩溃,根本没机会执行到输出逻辑。

错误出在quicksort函数的递归调用部分:

quicksort(array,r,q);

基准点r已经通过partition函数放到了正确的排序位置,不需要再参与右侧子数组的排序,应该改为:

quicksort(array,r+1,q);

修复后的完整代码:

#include <iostream>
#define SIZE 10
using namespace std;
void swap(int* a, int* b)
{
  int temp = *a;
  *a  = *b;
  *b = temp;
}
int partition(int* array,int p, int q)
{
   int key = array[p];
   int i = p;
   for(int j = p+1; j <= q; j++ )
   {
    if(key > array[j])
    {
       i++;
       swap(&array[i],&array[j]);
    }
   }
   swap(&array[i],&array[p]);
   return i;
}
void quicksort(int* array,int p,int q)
{
    if(p < q)
    {
     int r = partition(array,p,q);
     quicksort(array,p,r-1);
     quicksort(array,r+1,q); // 此处修改为r+1
    }
}
int main()
{
 int unsorted[SIZE] = {6,2,5,-1,11,3,17,-9,1,10};
 quicksort(unsorted,0,SIZE-1);
 cout << "The sorted array" << endl;
 for(int i = 0; i < SIZE; i++)
 {
    cout << unsorted[i] <<" ";
 }
 cout << endl;
}

修改后程序会正常完成排序,终端会输出:

The sorted array
-9 -1 1 2 3 5 6 10 11 17 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:40:37