Quick sort with middle element selected as the pivot

本秂侑毒 提交于 2019-12-13 03:44:09

问题


I have this code but the employer has asked me to pivot in the middle If anyone can help, please edit this code

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

回答1:


patel's answer switches from the question's Lomuto scheme to Hoare scheme. The simplest fix to the question's code would be swapping middle element with low element as the first line in partition

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



回答2:


change the partition method in the following way

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

D:



来源:https://stackoverflow.com/questions/57030369/quick-sort-with-middle-element-selected-as-the-pivot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!