【问题标题】:Why is this Quick Sort implementation giving a weird output为什么这个快速排序实现会给出一个奇怪的输出
【发布时间】:2020-04-11 06:27:36
【问题描述】:

我的快速排序给出了一个奇怪的输出。输出的某些部分已排序,而某些部分只是随机的。我正在使用 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;
}

【问题讨论】:

  • 这似乎是学习如何使用调试器逐语句逐句执行代码,同时监视变量及其值的好时机。这样您就可以轻松查看意外事件发生的时间和地点,例如越界索引或类似情况。
  • 这是一个单元测试:尝试排序:[0, 0, 0, 0]

标签: c++ algorithm recursion data-structures quicksort


【解决方案1】:

在这部分中,当您尝试从您拥有的位置开始对数组进行排序时

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);
}

【讨论】:

    猜你喜欢
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    相关资源
    最近更新 更多