Skip to content

Sorting Basics

Lesson 1 of 10 · 4 min

Sorting Basics

Step 1 of 5

Five records, in the order they arrived. Judge any sort on three things: time, extra memory and stability.

The Idea

Every comparison sort works by comparing pairs and rearranging them. Judge one on three things: time, extra memory, and stability. A stable sort keeps equal items in the order they arrived.

Real-World Example

Sort a spreadsheet by name, then sort it again by city. With a stable sort the names inside each city stay alphabetical; with an unstable one that earlier work is scrambled. Stability is what makes layered sorting possible at all.

The Code

Your turn

What does this print?

pairs = [("x", 2), ("y", 1), ("z", 2)]
out = sorted(pairs, key=lambda p: p[1])
print([p[0] for p in out])

Mini quiz

1 / 3

A stable sort guarantees that: