Heapsort Build And Extract Max (Python)
Sort a list by building a max heap in place then repeatedly extracting the maximum to the end.
Code
def heapsort(arr):
n = len(arr)
def sift_down(start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
if child + 1 <= end and arr[child] < arr[child + 1]:
child += 1
if arr[root] < arr[child]:
arr[root], arr[child] = arr[child], arr[root]
root = child
else:
return
for i in range((n - 2) // 2, -1, -1):
sift_down(i, n - 1)
for end in range(n - 1, 0, -1):
arr[0], arr[end] = arr[end], arr[0]
sift_down(0, end - 1)
return arrReport a problem with this exampleOpens a pre-filled issue on GitHub.