1. 程式人生 > 實用技巧 >python樹-堆排序

python樹-堆排序

程式碼

def heapSort(alist):
    heap = [0]
    heap.extend(alist)  # 直接將列表入堆,這樣葉子節點就不需要下沉
    heapSize = len(alist)
    i = heapSize // 2  # 下沉的順序必須是從底部到頂部
    while i > 0:  # 構建有序二叉堆
        sink(i, heap, heapSize)
        i = i - 1
    for i in range(len(alist)):
        alist[i] = delMin(heap, heapSize)
        heapSize = heapSize - 1  # 堆中元素不斷減小,堆得大小也需要不斷更新

def sink(index, heap, heapSize):  # 將index位置的元素沉底
    # print(heap)
    while index*2 <= heapSize:  # 保證不是葉子節點
        mi = getMin(index, heap, heapSize)  # 得到小兒子的索引
        if heap[index] > heap[mi]:
            heap[index], heap[mi] = \
            heap[mi], heap[index]
            index = mi
        else:
            break  # 如果父親比兩個兒子都小,迴圈停止

def getMin(index, heap, heapSize):  # 得到小兒子的索引
    if index*2+1 > heapSize:
        return index*2
    else:
        if heap[index*2] < heap[index*2+1]:
            return index*2
        else:
            return index*2+1

def delMin(heap, heapSize):  # 去頂+重構有序二叉堆
    temp = heap[1]  # 記錄即將遺失的變數(返回需要用到)
    heap[1] = heap[heapSize]  # 將尾部節點移至堆頂,準備下沉
    heap.pop()
    sink(1, heap, heapSize-1)  # 下沉堆頂元素
    return temp

l1 = [5, 2, 0, 1, 3, 1, 4]
heapSort(l1)
print(l1)

體會

用函式的方法實現堆排序,由於需要呼叫多個函式,而且呼叫的函式需要多個引數,不如用類的方法簡潔