算法导论第六章堆排序——Python实现

#堆排序

# 维护最大堆的性质
def max_heapify(A, i, heap_size):
    l = 2*i+1
    r = 2*i+2
    if l <= heap_size-1 and A[l] > A[i]:
        largest = l
    else:
        largest = i
    if r <= heap_size-1 and A[r] > A[largest]:
        largest = r
    if largest != i:
        temp = A[i]
        A[i] = A[largest]
        A[largest] = temp
        max_heapify(A, largest, heap_size)


def build_max_heap(A):  # 建堆
    heap_size = len(A)
    for i in range((heap_size-2)//2, -1, -1):  # 遍历非叶子节点
        max_heapify(A, i, heap_size)


def heapsort(A):
    build_max_heap(A)  # O(n)
    length = len(A)
    heap_size = length
    for i in range(length-1, 0, -1):
        temp = A[0]
        A[0] = A[i]
        A[i] = temp
        heap_size = heap_size - 1
        max_heapify(A, 0, heap_size)


A = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
heapsort(A)
print(A)

#最大优先队列

# 最大优先队列
def heap_maximum(A):  # 返回堆中最大元素
    return A[0]


def heap_extract_max(A, heap_size):  # 去掉并返回堆中最大元素
    if heap_size < 1:
        print("heap underflow")
    else:
        max_element = A[0]
        A[0] = A[heap_size - 1]
        heap_size = heap_size - 1
        max_heapify(A, 0, heap_size)
        return max_element


def heap_increase_key(A, i, key):  # A[i] = k, k必须大于A[i]
    if key < A[i]:
        print("new key is smaller than current key")
    else:
        A[i] = key
        parent = (i-1)//2
        while i > 0 and A[parent] < A[i]:
            temp = A[i]
            A[i] = A[parent]
            A[parent] = temp
            i = parent


def max_heap_insert(A, key):  # 在堆中插入key
    length = len(A)
    heap_size = length + 1
    A[heap_size - 1] = -float("inf")
    heap_increase_key(A, heap_size-1, key)


def heap_delete(A, i):  # 删除元素
    heap_size = len(A)
    temp = A[i]
    A[i] = A[heap_size-1]
    A[heap_size-1] = temp
    heap_size = heap_size - 1
    key = A[i]
    if key <= A[(i-1)//2]:
        max_heapify(A, i, heap_size)
    else:
        while i > 1 and A[(i-1)//2] < key:
            temp = A[i]
            A[i] = A[(i-1)//2]
            A[(i-1)//2] = temp
            i = (i-1)//2

A = [4, 1, 3, 2, 16, 9, 10, 14, 8, 7]
print(A)
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读