java - 为什么这种快速排序分区方法是错误的?

标签 java sorting quicksort

我有一个快速排序分区方法。 但我不明白为什么这是错误的

方法在这里:

private static <E extends Comparable<E>> int partition(E[] list, int first, int last) {
    int pivotIndex = (first + last) / 2;
    E pivot = list[pivotIndex]; // Choose the first element as the pivot
    swap(list, last, pivotIndex);
    pivotIndex = last;
    last--;
    do {
        // Search forward from left
        while (first < last && list[first].compareTo(pivot) <= 0)
            first++;
        // Search backward from right
        while (first <= last && list[last].compareTo(pivot) > 0)
            last--;

        // Swap two elements in the list
        if (last >= first) {
            swap(list, first, last);
            first++;
            last--;
        }
    } while (last > first);

    swap(list, pivotIndex, first);

    return first;
}

这就是使用递归调用的方式:

quickSort ( array )
quickSortRec( array, 0, array.size - 1 )
quickSortRec (array, left, right)
pivotIndex = findpivot(array, left, right) //use any method
newPivotIndex = partition ( array, left, right, pivotIndex )
if ( newPivotIndex - left > 1 )
quickSortRec( array, left, newPivotIndex - 1 )
if ( right - newPivotIndex > 1 )
quickSortRec( array, newPivotIndex + 1, right )

我知道 bug 存在于 do while 循环中,但我不知道为什么以及如何。我不需要正确版本的分区方法...我只是想知道为什么这个是错误的。例如,如果我想排序 [12 28 79 19 60 22 3 50 75 60 25 97 98 12 88 ] 它会给我 [3 12 19 22 25 12 28 50 60 60 75 79 88 97 98] 这是错误的......

最佳答案

在第一行,

int pivotIndex = (first + last) / 2;

pivotIndex 现在保存中间元素的位置。

E pivot = list[pivotIndex];

现在您将该值分配给数据透视表。

也许这就是您的代码给出错误答案的原因。

它只是将小于 50 的元素(即中间元素)放置在左侧,将大于 50 的元素放置在右侧。

关于java - 为什么这种快速排序分区方法是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33312464/

相关文章:

java - HTTP 状态 406。Spring MVC 4.0、jQuery、JSON

java - 是否可以在内核端比较两个 DFEVar 值

ruby - 按值的长度对散列进行排序(降序)

javascript - 如何对D3中的节点进行排序,以使连接路径清晰明了?

python - 在 Python 中在长排序的字符串列表中查找 'startswith' 子字符串的最快方法

algorithm - 算法的运行时间和输入大小如何告诉您算法的时间复杂度?

java - 通过传递用户 ID 列表来更新多个用户

Javascript 弹出功能

sorting - (快速)对 POSIX sh 中的文件列表进行排序

sorting - 为什么快速排序比基数排序更流行?