堆排序Python实现
实现步骤:
1.创建堆。这一步主要是实现创建一个大(小)根堆
2.调整堆。交换堆顶与堆末尾元素,然后调整堆使堆继续变成大(小)根堆
3.堆排序。利用上面2步完成堆排序的实现
# -*- coding:UTF-8 -*-
def heapInsert(arr, index):
"""
对第i个元素进行插入,然后进行调整,把它变成大根堆
"""
while arr[index] > arr[int((index - 1) / 2)]:
arr[index], arr[int((index - 1) / 2)] = arr[int((index - 1) / 2)], arr[index]
index = int((index - 1) / 2)
def heapAdjust(arr, index, size):
"""
调整堆使其继续变成大根堆
"""
left = index * 2 + 1
while left < size:
if left + 1 < size and arr[left + 1] > arr[left]:
largest = left + 1
else:
largest = left
if arr[largest] < arr[index]:
largest = index
if largest == index:
break
arr[largest], arr[index] = arr[index], arr[largest]
index = largest
left = index * 2 + 1
def heapSort(arr,size):
"""
堆排序实现
"""
if size < 2:
return
for i in range(0,size):
heapInsert(arr,i)
print("大根堆:",arr)
size = size - 1
arr[0], arr[size] = arr[size], arr[0]
while size > 0:
heapAdjust(arr, 0, size)
size = size - 1
arr[0], arr[size] = arr[size], arr[0]
if __name__ == '__main__':
a = [9, 12, -3, 0, 6, 8, 15, 7, 14,18]
a_size = len(a)
heapSort(a, a_size)
print("排序后:",a)