1. Concept library
  2. Data Structures & Algorithms
  3. Module 7: Sorting

Concept

Stability and comparators

A stable sort keeps equal elements in their original order, which matters when sorting by one field after another. A comparator or key function tells the sort what "smaller" means for your data.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a stable sort guarantees and when it matters
  2. Write a key function or comparator that sorts by one field
  3. Chain two sorts in the right order to sort by department then name

In practice

A few lines that show Stability and comparators doing its job.

Python
people = [("ada", 36), ("bob", 29), ("cy", 36)]

by_age = sorted(people, key=lambda p: p[1])
# [('bob', 29), ('ada', 36), ('cy', 36)]: ada stays before cy

# sort by age descending, then name ascending, in one key
ordered = sorted(people, key=lambda p: (-p[1], p[0]))

The common mistake

Watch for

Chaining sorts in the wrong order. To get "by department, then by name", sort by name first and by department second: the last sort wins and stability keeps the earlier one within ties.

What to know first

Your roadmap puts these before Stability and comparators, unless you already know them.

How it stays learned

Once a session shows you understand Stability and comparators, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Quicksort