【发布时间】:2020-04-11 06:27:36
【问题描述】:
我的快速排序给出了一个奇怪的输出。输出的某些部分已排序,而某些部分只是随机的。我正在使用 pivot 元素到 partition 数组递归使用 partition function 到 2 halves 与left half 元素小于枢轴元素,right half 元素大于枢轴元素。
#include <iostream>
using namespace std;
int partition(int *arr, int start, int end)
{
int pivot = start;
int temp;
int temp2;
while (start < end)
{
while (arr[start] <= arr[pivot])
start++;
while (arr[end] > arr[pivot])
end--;
if (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
temp2 = arr[pivot];
arr[pivot] = arr[end];
arr[end] = temp2;
return end;
}
void quickSort(int input[], int size)
{
int lb = 0;
int ub = size - 1;
int loc;
if (lb < ub)
{
loc = partition(input, lb, ub);
quickSort(input, loc - 1);
quickSort(input + loc + 1, ub - loc);
}
else
return;
}
int main()
{
int n;
cin >> n;
int *input = new int[n];
for (int i = 0; i < n; i++)
{
cin >> input[i];
}
quickSort(input, n);
for (int i = 0; i < n; i++)
{
cout << input[i] << " ";
}
delete[] input;
}
【问题讨论】:
-
这似乎是学习如何使用调试器逐语句逐句执行代码,同时监视变量及其值的好时机。这样您就可以轻松查看意外事件发生的时间和地点,例如越界索引或类似情况。
-
这是一个单元测试:尝试排序:
[0, 0, 0, 0]
标签: c++ algorithm recursion data-structures quicksort