Quick Sort

Pick a pivot, split the rest into smaller and larger, and sort each side the same way.

Python · intermediate · 8 min · 32 steps · free

What you'll learn

quick_sort.py

def quick_sort(items):
    if len(items) <= 1:
        return items
    pivot = items[0]
    smaller = [x for x in items[1:] if x < pivot]
    larger = [x for x in items[1:] if x >= pivot]
    return quick_sort(smaller) + [pivot] + quick_sort(larger)

print(quick_sort([4, 7, 2, 9, 1]))

Step by step

  1. Python defines the function quick_sort(). Its body does not run yet: it runs each time the function is called.
  2. Python calls quick_sort(), with items = [4, 7, 2, 9, 1]. It gets its own names.
  3. len(items) <= 1 is false, so the block under it is skipped.
  4. 4 is the pivot.
  5. Everything smaller than 4 goes into smaller: [2, 1].
  6. Everything else goes into larger: [7, 9].
  7. Sort smaller the same way.
  8. len(items) <= 1 is false, so the block under it is skipped.
  9. pivot is created with the value 2.
  10. smaller is created and points to a new list: [1].
  11. larger is created and points to a new list: [].
  12. Python calls quick_sort() #3, with items = [1]. It gets its own names.
  13. len(items) <= 1 is true, so the block under it runs.
  14. The function returns items.
  15. quick_sort() #3 has finished. Python calls quick_sort() #3, with items = []. It gets its own names.
  16. len(items) <= 1 is true, so the block under it runs.
  17. The function returns items.
  18. quick_sort() #3 has finished, so its names are gone.
  19. quick_sort() #2 has finished. Python calls quick_sort() #2, with items = [7, 9]. It gets its own names.
  20. len(items) <= 1 is false, so the block under it is skipped.
  21. pivot is created with the value 7.
  22. smaller is created and points to a new list: [].
  23. larger is created and points to a new list: [9].
  24. Python calls quick_sort() #3, with items = []. It gets its own names.
  25. len(items) <= 1 is true, so the block under it runs.
  26. The function returns items.
  27. quick_sort() #3 has finished. Python calls quick_sort() #3, with items = [9]. It gets its own names.
  28. len(items) <= 1 is true, so the block under it runs.
  29. The function returns items.
  30. quick_sort() #3 has finished, so its names are gone.
  31. quick_sort() #2 has finished, so its names are gone.
  32. smaller + [pivot] + larger, at every level, gives the sorted list.

Common mistakes

Best practices

Key takeaways

Check yourself

Quick sort on sorted input with first-item pivot?

Answer: O(n²). Every split is lopsided.

Where is the pivot after partitioning?

Answer: In its final place

·

More in Sorting