← Back to Heaps

Sort Using a Heap

4 of 6

Exercise 3: Sort Using a Heap πŸ“Š

Your Task

Write a function heap_sort(nums) that sorts a list in ascending order using only heap operations.

Rules:

  • βœ… Use heapq
  • ❌ Do NOT use .sort() or sorted()

Examples

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]

Hints


Bonus Challenge 🌟

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]

Try it yourself

Code: Sort Using a Heap

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...