我该如何修复这个快速排序功能?

时间:2013-11-14 21:19:10

标签: c algorithm 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程序,打印出类似数组的内容

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

enter image description here

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

quickSort(bars, barCount, 1, 10);

enter image description here

我的问题:

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

1 个答案:

答案 0 :(得分:2)

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

quickSort(bars, barCount, 0, 9);

或者最好

quickSort(bars, barCount, 0, barCount - 1);
相关问题