Lecture Notes — Lecture 18: Sorting as an Idea

Companion to the lecture plan and the worked examples. Read the Definitions before class, the Explanation after it; the practice questions and the lecture quiz close the loop.

Definitions

Explanation

Sorting is a family, not a function. The lecture builds three intuitions - select the smallest, insert into a sorted prefix, merge two sorted runs - before naming any real algorithm.

Stability is the quiet hero. Sort by name, then by score, and equal scores stay alphabetical - because each pass is stable. Unstable sorts force composite keys; the leaderboard case shows both paths.

Merge is where the speed comes from. Merging two sorted halves is linear; halving the problem log n times gives n log n total. The merge itself is done on paper with two fingers.

The merge rule and its tie-break. Take from the left run when values are equal (or the tie-break says otherwise); arbitrary choices break stability and reproduce-ability.

Almost-sorted inputs are special. Insertion sort on nearly-sorted data is nearly linear - a practical lesson: measure your data's shape before choosing a method.

Examples

The lecture's worked examples live in examples.md; the case studies this lecture builds on are worked in class from the projector. The case sequence with difficulties:

Common misconceptions

Summary and key takeaways

  1. Three intuitions: select, insert, merge - every sort is one of these plus engineering.
  2. Stability composes multi-key sorts; check it before relying on it.
  3. Merging is linear; halving logarithmically gives n log n.
  4. Nearly-sorted data changes the best choice - measure the shape.

Practice questions

Where this leads

Next lecture: Two Pointers and Invariants. The quiz below checks this lecture's essentials before we build on them.