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
| def max_heap_down(arr, current, size): max = current left = current * 2 + 1 right = left + 1 if left <= size and arr[max] < arr[left]: max = left if right <= size and arr[max] < arr[right]: max = right if max != current: arr[max], arr[current] = arr[current], arr[max] max_heap_down(arr, max, size)
def heap_sort_asc(arr, size): for i in range(int(size / 2 - 1), -1, -1): max_heap_down(arr, i, size - 1) print(arr) for i in range(size - 1, 0, -1): arr[0], arr[i] = arr[i], arr[0] max_heap_down(arr, 0, i - 1) print(arr)
if __name__ == '__main__': arr = [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48] print('原始数组:', arr) heap_sort_asc(arr, len(arr)) print('排序后数组:', arr)
|