def swapNode(arr, node1, node2):
temp = arr[node1]
arr[node1] = arr[node2]
arr[node2] = temp
def moveMaxNode(arr, location):
maxNode = 0
if arr[location - 1] < arr[location * 2 - 1] or arr[location - 1] < arr[location * 2]:
if arr[location * 2 - 1] < arr[location * 2]:
maxNode = location * 2
else:
maxNode = location * 2 - 1
swapNode(arr, location - 1, maxNode)
def moveFirstNode(arr, firstNotLeapNode, length):
if length % 2 == 0:
if arr[firstNotLeapNode - 1] < arr[firstNotLeapNode * 2 - 1]:
swapNode(arr, firstNotLeapNode - 1, firstNotLeapNode * 2 - 1)
else:
moveMaxNode(arr, firstNotLeapNode)
def buildHeap(arr, length):
layer = 1
firstNotLeapNode = length // 2
while layer <= firstNotLeapNode:
moveFirstNode(arr, firstNotLeapNode, length)
for i in range(firstNotLeapNode - 1, layer - 1, -1):
moveMaxNode(arr, i)
layer = 2 ** layer
# for i in range(0, firstNotLeapNode):
# moveFirstNOde(arr, firstNotLeapNode, length)
# for j in range(firstNotLeapNode - 1, i, -1):
# moveMaxNode(arr, j)
def heapSort(arr):
length = len(arr)
originalLength = length
for i in range(originalLength):
buildHeap(arr, length)
temp = arr[0]
arr[0] = arr[length - 1]
arr[length - 1] = temp
length -= 1
# arr = [49, 38, 65, 97, 76, 13, 27, 49, 10]
# heapSort(arr)
# print(arr)
arr = [49, 38, 65, 97, 76, 13, 27, 49, 10, 12]
heapSort(arr)
print(arr)
Python 堆排序
于 2022-04-09 18:54:30 首次发布