Foundation · Module 4 · Lesson 8

Stability & in-place trade-offs

Choose a sort using more than runtime alone.

15–25 min readLesson 26 of 123

Lesson 26 of 123

1d streak

Theory lesson · Step-by-step

Understand Stability & in-place trade-offs

Choose a sort using more than runtime alone.

Worked approach

Trace the reasoning step by step

  1. 1Identify the sorted region maintained by Stability & in-place trade-offs.
  2. 2Choose or compare the next candidate according to the algorithm.
  3. 3Move values while preserving multiplicity and ordering requirements.
  4. 4Grow the sorted region and prove that at least one value becomes final.
  5. 5Check duplicates, stable-order requirements, sorted input, and reverse input.

Concrete example

Sort records [(2,A),(1,B),(2,C)] by number.

  1. 1A stable sort keeps A before C.
  2. 2An unstable swap may reverse equal-key records.

Stable result is [(1,B),(2,A),(2,C)].

What must remain true (Loop Invariant)

After each stage of Stability & in-place trade-offs, the declared sorted region is final and the remaining values still contain every unplaced element.

Cost Model

Complexity & Trade-offs

Choose and run sort
Algorithm-dependent
Algorithm-dependent
The bound follows from the number of states visited and the work performed per transition.

When to use it

  • Creating order before searching, grouping, deduplicating, or scanning.
  • Selecting records using stability, memory, and input-shape constraints.
  • Turning pairwise decisions into monotonic scans.

Common mistakes

  • Comparing time alone while ignoring stability and auxiliary memory.
  • Breaking duplicate order when stability is required.
  • Quoting average performance without worst-case behavior.

Practice prompts

  • Reproduce the worked Stability & in-place trade-offs example without looking at the trace.
  • Change one input condition and explain whether the Stability & in-place trade-offs invariant still holds.
  • Implement the approach, derive its cost, and compare it with a straightforward baseline.

Mastery check

Can you derive it instead of memorizing it?

State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.