python - 当多个值等于枢轴时,Hoare 分区不起作用

标签 python algorithm sorting quicksort hoare-logic

我正在尝试编写自己的 hoare 分区函数以更好地理解它。我以为我很好地遵循了它的定义和伪代码,但即使它在很多情况下似乎都按预期工作,但当传入一个具有多个等于 pivot 的值的列表时,它会分崩离析并进入无限循环。我的错误在哪里,我应该如何修改它来修复错误?

def partition(lst, left_index, right_index):
    pivot = lst[right_index]


    while True:
        #Increment left index until value at that index is greater or equal to pivot
        while True:
            if lst[left_index] >= pivot: break
            left_index += 1

        #Increment right index until value at that index is less or equal to pivot
        while True:
            if lst[right_index] <= pivot: break
            right_index -= 1

        if left_index < right_index:
            lst[left_index], lst[right_index] = lst[right_index], lst[left_index]
        else:
            return right_index

return partition(0, end)

最佳答案

您正在测试 lst[left_index] >= pivot 中的枢轴值是否相等和 lst[right_index] <= pivot .这有效地防止了两个索引跳过枢轴值元素。因此,当两个或多个枢轴值元素被推向列表的中间时,left_indexright_index被无法逾越的障碍隔开。删除其中一个 break 中的等号ing 行,非停机问题将消失。

但是,由于此更改,移动的循环 left_index可以将它推高一个位置 right_index甚至在 right_index 时出界停留在初始位置。同样,移动 right_index 的循环可以将它推到低于 left_index 的位置甚至在 left_index 时出界停留在初始位置。为防止这种情况发生,您必须更改 while True:在这些循环中到 while left_index < right_index: .

请注意,根据您是否删除 left_index 的相等性检查,分区会略有不同。或 right_index .当枢轴元素是列表中的最小值或最大值时,它对边界情况很重要。考虑到一开始right_index表示相对于输入范围的内部位置,left_index指向边界位置,必须允许 left_index跳过枢轴值,而 right_index必须指示在枢轴值处停止(相反的逻辑将使 left_index 保持在其初始位置直到算法结束,而 right_index 可以一直向下推到 left_index ,不产生任何分区) .

因此更正后的代码将是这样的:

def partition(lst, left_index, right_index):
    pivot = lst[right_index]

    while True:
        while left_index < right_index and lst[left_index] <= pivot:
            left_index += 1

        while left_index < right_index and lst[right_index] > pivot:
            right_index -= 1

        if left_index < right_index:
            lst[left_index], lst[right_index] = lst[right_index], lst[left_index]
        else:
            return right_index

关于python - 当多个值等于枢轴时,Hoare 分区不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38287201/

相关文章:

python - Arff 装载机 : AttributeError: 'dict' object has no attribute 'data'

python - Pyramid 项目内的外部 iFrame。更新后没有刷新

c - 用 C 语言编写一个程序,应用 Luhn 算法进行信用卡验证

algorithm - 布局许多不规则的盒子,使它们适合屏幕

javascript - 将超集数组叠加到顺序/顺序很重要的子集数组上(在 Javascript 中)

c++ - 桶排序和计数排序的场景

java - 如何对字符串列表进行排序并在 Java 中找到 1000 个最常见的值

python - Python 上的 io.open() 和 os.open() 有什么区别?

python - 更有效的数据结构/算法在数据库中查找相似的图像哈希

java - 如何判断2个不同的单词是否具有相同的字母?