【发布时间】:2017-01-14 12:01:33
【问题描述】:
我的快速排序算法有问题。代码编译没有任何错误,但是当我尝试运行程序时,我得到的唯一输出是“随机数是:”,然后就像它想要用户输入一样,然后我必须终止程序。现在,当我在主程序中删除对快速排序函数的调用时,程序会打印出数字,但不能与快速排序函数的调用一起使用。我不确定我使用的参数是问题还是函数本身。
#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;
}
【问题讨论】:
-
一个建议:普通的
l(小写字母L)看起来很像1,这在阅读代码时会令人困惑。
标签: c++ algorithm function sorting quicksort