📜  堆排序 python 代码示例

📅  最后修改于: 2022-03-11 14:45:54.084000             🧑  作者: Mango

代码示例1
def buildHeap(lista, n):
    for i in range(n//2 - 1, -1, -1):
        heapify(lista, n, i)

def heapify(lista, n, i):
    largest = i  
    left = (2 * i) + 1    
    right = (2 * i) + 2 

    if left < n and lista[largest] < lista[left]:
        largest = left

    if right < n and lista[largest] < lista[right]:
        largest = right

    if largest != i:
        lista[i], lista[largest] = lista[largest], lista[i] 
        heapify(lista, n, largest) 

def heapSort(lista):
    n = len(lista)
    buildHeap(lista, n)
    
    for i in range(n-1, 0, -1):
        lista[i], lista[0] = lista[0], lista[i]
        heapify(lista, i, 0)