为什么这个快速排序实现给出了一个奇怪的输出

Why is this Quick Sort implementation giving a weird output

本文关键字:一个 输出 快速排序 实现 为什么      更新时间:2023-10-16

我的快速排序给出了一个奇怪的输出。输出的某些部分是排序的,而某些部分只是随机的。我正在使用pivot元素递归地partition数组,使用partition function2 halvesleft 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);
}