def heapify(arr, num_node, node):
if (node >= num_node):
return
child_left = 2 * node + 1
child_right = 2 * node + 2
max = node
if (child_left < num_node and arr[child_left] > arr[max]):
max = child_left
if (child_right < num_node and arr[child_right] > arr[max]):
max = child_right
if (max != node):
swap(arr, max, node)
heapify(arr, num_node, max)
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def bulid_heap(arr, num_node):
last_node = num_node - 1
parent_node = (last_node - 1) // 2
for i in range(parent_node, -1, -1):
heapify(arr, num_node, i)
def heap_sort(arr, num_node):
bulid_heap(arr, num_node)
end = num_node - 1
for i in range(end, -1, -1):
swap(arr, i, 0)
heapify(arr, i, 0)
if __name__ == "__main__":
list = [9,1,2,2,6,6,5,7,3,6,8,4]
print(list)
heap_sort(list, len(list))
print(list)
堆排序 | python
最新推荐文章于 2024-09-04 21:39:45 发布