c++ - 为什么这个快速排序实现会给出一个奇怪的输出
问题描述
我的快速排序给出了一个奇怪的输出。输出的某些部分是排序的,而某些部分只是随机的。我正在使用数组中的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);
这意味着 input[loc] 永远不会被处理,因为你从 0 到 loc -1 和 loc +1 到 end
在这里更正
if (lb < ub)
{
loc = partition(input, lb, ub);
quickSort(input, loc );
quickSort(input + loc + 1, ub - loc);
}
推荐阅读
- python - 在python中为时间序列图添加水平限制线
- python-3.x - Sanic Web 框架性能
- java - 将自定义数量的数组对象添加到 v.findViewById(R.id.iterateHere1) 而不重复代码
- dji-sdk - 有什么方法可以将实时遥测数据从 DJI Mavic 2 Zoom 获取到另一个设备,比如电脑?
- javascript - 如何在 React Native 0.61 中自定义 react-native-gifted-chat
- fpga - 如何在 FPGA 中从 2 MHz 时钟生成 4 MHz 时钟
- c++ - 运算符继承问题和 cpp 核心指南 c.128
- apache-kafka - 如何使用具有数组属性类型的 ksql 进行过滤
- python - 无法使用python操作mysql
- amazon-web-services - 为什么 rds 在 aws 的 3 个子网中