快速排序,中间元素被选为枢轴

时间:2019-07-14 19:12:52

标签: python python-3.x algorithm sorting quicksort

我有此代码,但雇主要求我在中间进行调整 如果有人可以提供帮助,请修改此代码

def quicksort(sequence, low, high):
    if low < high:
        pivot = partition(sequence, low, high)
        quicksort(sequence, low, pivot - 1)
        quicksort(sequence, pivot + 1, high)

def partition(sequence, low, high):
    pivot = sequence[low]
    i = low + 1
    for j in range(low + 1, high + 1):
        if sequence[j] < pivot:
            sequence[j], sequence[i] = sequence[i], sequence[j]
            i += 1
    sequence[i-1], sequence[low] = sequence[low], sequence[i-1]
    return i - 1

2 个答案:

答案 0 :(得分:1)

patel的答案从问题的Lomuto方案切换到Hoare方案。问题代码的最简单解决方法是将中间元素与低位元素交换为分区的第一行

def partition(sequence, low, high):
    sequence[low],sequence[(low+high)//2] = sequence[(low+high)//2],sequence[low] #change
    pivot = sequence[low]
      ...

答案 1 :(得分:1)

通过以下方式更改分区方法

def partition(sequence, low, high):
    sequence[low],sequence[(low+high)//2] = sequence[(low+high)//2],sequence[low]
    pivot = sequence[low]

D: