Course contentsShow
← Computer Science
Lesson 738 of 2,87218. Sorting AlgorithmsFree lesson

Stability in Sorting

Defining stable vs unstable sorts and why preserving relative order of equal elements matters in practice.

Stability in Sorting

You'll learn: Why some sorting algorithms preserve the original order of equal elements—and when that matters.

The Core Idea

A stable sort guarantees that when two elements compare as equal, they appear in the output in the same relative order as they did in the input. An unstable sort makes no such promise—equal elements might get shuffled around.

Imagine sorting students by test score. Alice and Bob both scored 85. In the original list, Alice came before Bob. A stable sort keeps Alice before Bob in the sorted output. An unstable sort might swap them—Alice could end up after Bob, even though both have the same score.

Why Does This Matter?

Stability becomes critical when you're sorting data that has multiple attributes.

Suppose you already sorted employees by name, and now you sort by department. With a stable sort, employees within each department remain alphabetically ordered by name. With an unstable sort, that previous name ordering gets lost—you'd need to sort by both criteria simultaneously.

Real-world examples:

  • Sorting transactions by date, then by amount—stability preserves chronological order within each amount group
  • Sorting database records on multiple columns sequentially
  • Maintaining user-perceived order in UI lists when secondary sorting is applied

Stable vs Unstable Algorithms

Some sorting algorithms are inherently stable (like the ones you'll learn soon), while others are naturally unstable. You can sometimes make an unstable algorithm stable by attaching index numbers to track original positions—but that adds overhead.

Key Takeaway: A stable sort preserves the relative order of equal elements from input to output, which is essential when sorting by multiple criteria or maintaining meaningful secondary orderings.