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 arrHow the snippet works
Structurally, expect the functions heapsort and sift_down and nothing else.
Iteration happens inside while root * 2 + 1 <= end — everything outside it runs once.
Applying it
The main signature reads def heapsort(arr)
heapsort is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `heapsort`, `sift_down` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.