← 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

πŸ’‘ Hint 1

A min-heap always pops the smallest element. If you keep popping until it's empty, what order do the elements come out in?

πŸ’‘ Hint 2 β€” Step by step
  1. Copy the list (so you don't destroy the original)
  2. heapq.heapify() the copy β€” this is O(n)
  3. Pop all elements one by one into a result list
  4. Return the result
βœ… Solution
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! 🧠


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...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… 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