为什么这个快速排序实现给出了一个奇怪的输出
Why is this Quick Sort implementation giving a weird output
我的快速排序给出了一个奇怪的输出。输出的某些部分是排序的,而某些部分只是随机的。我正在使用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;
}
在这一部分中,当您尝试从位置开始对数组进行排序时,您拥有
quickSort(input, loc - 1);
quickSort(input + loc + 1, ub - loc);
这意味着输入[loc]永远不会被处理,因为你从0到loc -1和loc +1到结束
此处已更正
if (lb < ub)
{
loc = partition(input, lb, ub);
quickSort(input, loc );
quickSort(input + loc + 1, ub - loc);
}
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 我写了一个C++程序来模拟Enigma机器.我没有得到输出
- 如何使用C++读取另一个程序中的源代码输出
- 我从int x[3]得到的一个非常奇怪的输出;
- Qt creator 4.11,在应用程序输出面板中创建一个链接
- 我的输出中有一个额外的 0,为什么会这样
- 以C++输出一个数字三角形
- 当使用我在一个函数、另一个函数中修改的数组时,在我的输出中得到一个奇怪的负数
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- C++:为什么最后一个输出不是地址以及如何获取值 9
- 如何仅使用循环/控制语句和两个cout语句创建一个倒三角:一个输出“#”和一个输出' n'
- 如何制作一个输出流,将未指定的类型括在C++的括号内
- C++我在运行时创建一个输出文件,如何再次读取此输出文件作为输入
- 我不明白这段代码的最后一个输出
- 将两个正则表达式结果连接到一个输出字段中,一次只能使用一个
- 为什么我得到一个输出"b(1) dc dvfunc"?
- 矩阵从一个输入文件到LAPACK,再反向到一个输出文件
- 从文件流创建一个输出文件