繁体   English   中英

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

[英]How should I fix this quicksort 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);
}

为了了解它是如何printBars ,我编写了一个printBars过程,该过程可以像这样打印数组的内容

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

在此处输入图片说明

我在前面提到的数组bars[]上运行quickSort之后的最终结果是此图形

quickSort(bars, barCount, 1, 10);

在此处输入图片说明

我的问题:

  1. 10去了哪里?
  2. 为什么值之一是0 (原始数组没有)?

数组索引从零开始。 所以你只想更正你的电话

quickSort(bars, barCount, 0, 9);

或最好

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

暂无
暂无

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

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