1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
def reconstruct_max_heap(array, end, root): """ :param array: list :param end: int, the heap last node pos :param root: int, heap root :return: None """ left_sub_root = root * 2 right_sub_root = root * 2 + 1 largest = root
if left_sub_root <= end and array[left_sub_root] > array[root]: largest = left_sub_root
if right_sub_root <= end and array[right_sub_root] > array[largest]: largest = right_sub_root
if largest != root: array[root], array[largest] = array[largest], array[root] reconstruct_max_heap(array, end, largest)
def build_max_heap(array): """ :param array: list :return: list """ n = len(array) cur = n // 2 while cur >= 0: reconstruct_max_heap(array, n-1, cur) cur -= 1
return array
def heap_sort(array): """ Ascending order sort. :param array: list :return: list """ build_max_heap(array)
end = len(array) - 1 while end >= 1: array[0], array[end] = array[end], array[0]
end -= 1
reconstruct_max_heap(array, end, 0)
return array
if __name__ == "__main__": li = [5, 13, 2, 25, 7, 17, 20, 8, 4] heap_sort(li) print(li)
|