排序算法(七):堆排序

def adjust_heap(arr, i, size):
    lchild = 2 * i + 1
    rchild = 2 * i + 2
    max = i
    if i < size / 2:
        if lchild < size and arr[lchild] > arr[max]:
            max = lchild
        if rchild < size and arr[rchild] > arr[max]:
            max = rchild
        if max != i:
            arr[max], arr[i] = arr[i], arr[max]
            adjust_heap(arr, max, size)

def build_heap(arr, size):
    for i in range(0, round(size / 2))[::-1]:
        adjust_heap(arr, i, size)

def heap_sort(arr):
    size = len(arr)
    build_heap(arr, size)
    for i in range(0, size)[::-1]:
        arr[0], arr[i] = arr[i], arr[0]
        adjust_heap(arr, 0, i)
    return arr

你可能感兴趣的:(排序算法(七):堆排序)