快速排序算法问题
Quicksort algorithm issue
我的快速排序算法有问题。代码编译没有任何错误,但是当我尝试运行程序时,我得到的唯一输出是"随机数是:",然后表现得好像它需要用户输入,然后我必须终止程序。现在,当我在主程序中删除对快速排序函数的调用时,程序会打印出数字,但是不能调用快速排序函数。我不确定是否我使用的参数是问题,或者如果它是函数本身。
#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::endl
到cout
,它们可能会被打印出来。)
我怀疑这就是问题所在:
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
)。
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 到连接组件算法的问题(递归)
- 读取最后一行代码算法 - c++ 时出现问题
- 需要为 C++ 中的以下问题设计递归算法
- 我的C++语言蛮力算法有问题
- Coursera DSA 算法工具箱第 4 周第 2 个问题 - 分区纪念品
- 排序算法问题(购买商店物品)(崩溃)
- C++ 分而治之的算法问题
- 我对 std::unique(算法)C++有问题
- 对于这个问题,是否有更好的数据结构和算法选择
- 迭代快速排序方法的分区算法问题
- 这种快速排序算法有什么问题?
- 不确定我的排序算法出了什么问题
- 我的算法在 1D 数组中渲染矩形有什么问题
- 带有 std::vector 和 std::queue 的 Prim's 算法,我的代码有什么问题?
- 我的记忆动态规划算法有什么问题?
- 运行Dijkstra算法的问题
- 关于合并两个列表的算法的一些问题
- 函数以相反的顺序输出输入问题,并改进算法以解释相等的数字
- 分类算法和对象指针的问题