一尘不染

实现快速排序算法

algorithm

我从这本书中找到了快速排序算法

这是算法

QUICKSORT (A, p, r)
if p < r
    q = PARTITION(A, p, r)
    QUICKSORT(A, p, q-1)
    QUICKSORT(A, q+1, r)

PARTITION(A, p, r)
x=A[r]
i=p-1
for j = p to r - 1
  if A <= x
     i = i + 1
     exchange A[i] with A[j]
exchange A[i+1] with A[r]
return i + 1

我做了这个C#代码:

private void quicksort(int[] input, int low, int high)
{
    int pivot_loc = 0;

    if (low < high)
        pivot_loc = partition(input, low, high);
    quicksort(input, low, pivot_loc - 1);
    quicksort(input, pivot_loc + 1, high);
}

private int partition(int[] input, int low, int high)
{
    int pivot = input[high];
    int i = low - 1;

    for (int j = low; j < high-1; j++)
    {
        if (input[j] <= pivot)
        {
            i++;
            swap(input, i, j);
        }
    }
    swap(input, i + 1, high);
    return i + 1;
}



private void swap(int[] ar, int a, int b)
{
    temp = ar[a];
    ar[a] = ar[b];
    ar[b] = temp;
}

private void print(int[] output, TextBox tbOutput)
{
    tbOutput.Clear();
    for (int a = 0; a < output.Length; a++)
    {
        tbOutput.Text += output[a] + " ";
    }
}

当我这样调用函数时,quicksort(arr,0,arr.Length-1);我会收到此错误,An unhandled exception of type 'System.StackOverflowException' occurred它将传递空数组…当quicksort(arr,0,arr.Length);我这样调用函数时,我将Index was outside the bounds of the array.在此行获取错误,int pivot = input[high];但数组传递成功。

我也想像这样打印它,print(input,tbQuick);但是在快速排序完成后可以打印在哪里放置呢?


阅读 222

收藏
2020-07-28

共1个答案

一尘不染

您没有正确实现基本案例终止,这会导致quicksort永不停止重复其长度为0的子列表。

更改此:

if (low < high)
    pivot_loc = partition(input, low, high);
quicksort(input, low, pivot_loc - 1);
quicksort(input, pivot_loc + 1, high);

对此:

if (low < high) {
    pivot_loc = partition(input, low, high);
    quicksort(input, low, pivot_loc - 1);
    quicksort(input, pivot_loc + 1, high);
}
2020-07-28