简体   繁体   English

我应该如何修复此快速排序功能?

[英]How should I fix this quicksort function?

Following online resources on the quicksort algorithm, I've reconstructed the following function: 遵循有关quicksort算法的在线资源,我重构了以下功能:

void quickSort(int *array, int arrayLength, int first, int last) {

    int pivot, j, i, temp;
    if (first < last) {
        pivot = first;
        i = first;
        j = last;

        while (i < j) {
            while (array[i] <= array[pivot] && i < last) {
                i++;
            }
            while (array[j] > array[pivot]) {
                j--;
            }
            if (i < j) {
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }

        temp = array[pivot];
        array[pivot] = array[j];
        array[j] = temp;
        quickSort(array, arrayLength, first, j-1);
        quickSort(array, arrayLength, j+1, last);
    }
    printBars(array, arrayLength);
}

To see how it does its magic, I've written a printBars procedure, that prints contents of an array like so 为了了解它是如何printBars ,我编写了一个printBars过程,该过程可以像这样打印数组的内容

int bars[] = {2, 4, 1, 8, 5, 9, 10, 7, 3, 6};
int barCount = 10;
printBars(bars, barCount);

在此处输入图片说明

The final result after i run quickSort on the previously mentioned array bars[] is this graphic 我在前面提到的数组bars[]上运行quickSort之后的最终结果是此图形

quickSort(bars, barCount, 1, 10);

在此处输入图片说明

My questions: 我的问题:

  1. Where did 10 go? 10去了哪里?
  2. Why is there a 0 as one of the values (original array didn't have it)? 为什么值之一是0 (原始数组没有)?

Array indices are zero-based. 数组索引从零开始。 So you just want to correct your call 所以你只想更正你的电话

quickSort(bars, barCount, 0, 9);

or preferably 或最好

quickSort(bars, barCount, 0, barCount - 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM