快速排序算法问题

Quicksort algorithm issue

本文关键字:问题 算法 快速排序      更新时间:2023-10-16

我的快速排序算法有问题。代码编译没有任何错误,但是当我尝试运行程序时,我得到的唯一输出是"随机数是:",然后表现得好像它需要用户输入,然后我必须终止程序。现在,当我在主程序中删除对快速排序函数的调用时,程序会打印出数字,但是不能调用快速排序函数。我不确定是否我使用的参数是问题,或者如果它是函数本身。

#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <stack>
#include <queue>
using namespace std;
void quicksort(int arr[], int left, int right) {
  int l = left;
  int r = right;
  int tmp;
  int pivot = arr[(left + right) / 2];
  while (l <= r) {
    while (arr[l] < pivot)
      l++;
    while (arr[l] > pivot)
      r--;
    if (l <= r) {
      tmp = arr[l];
      arr[l] = arr[r];
      arr[r] = tmp;
      l++;
      r--;
    }
  }
  if (left < r)
    quicksort(arr, left, r);
  if (l < right)
    quicksort(arr, r, right);
}
int main() {
  int n = 20;
  int testlist[n];
 for (int i = 0; i<n; i++) {
   testlist[i] = rand()%100;
 }
 cout << "The random numbers are: " << endl;
 for (int i = 0; i < n; i++) cout << testlist[i] << " ";

 quicksort(testlist, 0, n - 1);
 cout << " " << endl;
 cout << "The sorted numbers are: " << endl;
 for (int i = 0; i < n; i++) {
   cout << testlist[i] << " ";
 }
 return 0;
}

您的quicksort函数中有一个无限循环。由于这个函数永远不会返回,因此在"随机数是:"行之后没有任何内容被打印,因为quicksort调用永远不会返回。随机数本身可能打印,也可能不打印(在我的系统上确实打印),因为系统不能保证立即将输出缓冲区刷新到屏幕上。(如果您在打印数字的for循环之后写入std::endlcout,它们可能会被打印出来。)

我怀疑这就是问题所在:

while (arr[l] > pivot)
    r--;

语句while (arr[l] > pivot)实际上应该是while (arr[r] > pivot)

这是因为quicksort()内部出了问题,您在没有std::endl 的情况下打印了数字 !

您可以看到,没有std::endl,这些数字被写入输出缓冲区,但它们不会被刷新。他们最终会,没有std::endl,但你的代码没有做到这一点。

专业提示:总是使用std::endl当你调试你的代码!


我不会调试你的quicksort(),因为你应该这样做,为了练习!如果你需要一个参考,你可以使用我的小例子:Quicksort (c++),它是用类似C的方式编写的,所以C和c++的人都可以很容易地学习!:)

Hunch:你使用递归,你的程序不会终止…无限循环可能是原因…;)


顺便说一句,如果我是你,没有什么重要的理由使用:

#if __INCLUDE_LEVEL__ < 1

我将放弃它(连同伴随的#endif)。