4 of 6
Write a function heap_sort(nums) that sorts a list in ascending order using only heap operations.
Rules:
heapq.sort() or sorted()print(heap_sort([5, 3, 8, 1, 4, 2, 7])) # Output: [1, 2, 3, 4, 5, 7, 8] print(heap_sort([10, 1, 10, 1])) # Output: [1, 1, 10, 10] print(heap_sort([42])) # Output: [42]
A min-heap always pops the smallest element. If you keep popping until it's empty, what order do the elements come out in?
heapq.heapify() the copy β this is O(n)import heapq def heap_sort(nums): heap = nums[:] heapq.heapify(heap) return [heapq.heappop(heap) for _ in range(len(heap))]
Why this works: heapify arranges the list so the smallest is at the front. Each heappop removes the smallest remaining element, so you get everything in sorted order!
Time: O(n log n) β same as regular sort, but now you understand why it works! π§
Sort in descending order using a heap. (Hint: negate trick!)
print(heap_sort_desc([5, 3, 8, 1, 4])) # Output: [8, 5, 4, 3, 1]
β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit