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

标签 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

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

quickSort(bars, barCount, 1, 10);

enter image description here

我的问题:

  1. 10 去哪儿了?
  2. 为什么有一个 0 作为值之一(原始数组没有它)?

最佳答案

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

quickSort(bars, barCount, 0, 9);

或者最好

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

关于c - 我应该如何修复此快速排序功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19988602/

相关文章:

algorithm - 如何计算此聚类中总误差的度量

python - 文本分割 : Algorithm to match input with the longest words from the dictionary

algorithm - 如何使用快速排序找到 K 个最小值

algorithm - 多维快速排序算法

c - 修改 detab 以接受制表位列表

c - 在 Windows 中用 C 守护进程

c - 如何正确比较 C 中的字符串?

c# - 计算实体的频率和新近度的算法?

c - 如何将浮点值四舍五入到最接近的十进制值?

algorithm - 修改此快速排序以始终使用最后一个元素作为基准