这是heapsort的python3实现,其中n是堆的大小。
def heapify(arr, n, i):
largest = i
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and arr[i] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
我了解保健功能和它在做什么。但我在max heap中发现了一个问题:
^{pr2}$根据我的研究,我认为我需要建立最大堆只在非叶节点,这应该是0。。。n/2.那么这里的范围正确吗?
我也很难理解最后一部分:
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
从n-1开始这个范围是怎么工作的。。。0的步骤=-1?
c++堆排序的GeeksforGeeks代码
参考文献:-
CLRS书籍中Heapsort的伪代码
^{pr2}$所以是的,你是对的。只有不愈合的叶子才足够强壮。在
至于你的第二个呢问题:在
伪代码
相关问题 更多 >
编程相关推荐