Course contentsShow
← C
Lesson 1052 of 1,21914. Data Structures in CFree lesson

Stability in sorting algorithms

Stability in sorting algorithms

What you'll learn: How to identify whether a sorting algorithm preserves the original order of "equal" elements.

The "Identical" Problem

In C, we often sort data that isn't just a simple list of integers. We sort structs. Imagine you have a list of students, and each student has a name and a grade.

If you sort this list by grade, what happens to two students who both have a 90? Do they stay in the same relative order they were in before the sort, or does the algorithm shuffle them?

A stable sorting algorithm guarantees that if two items have the same key (the value you are sorting by), their relative order remains unchanged. An unstable algorithm makes no such promise.

A Concrete Analogy

Think of a deck of cards. You lay them out on a table in this order:

  1. 5 of Hearts
  2. 3 of Diamonds
  3. 5 of Spades

If you sort these by number using a stable sort, the 5 of Hearts must come before the 5 of Spades, because it was ahead of it originally. If you use an unstable sort, the 5 of Spades might end up first. While they are both "5s," their original positions have been lost.

Why Does It Matter?

Stability is crucial when performing multi-pass sorts. For example, if you want to sort a list of employees by Department and then by Last Name, you would first sort by name, then perform a stable sort by department. Because the second sort is stable, the alphabetical order within each department is preserved.

Code Representation

While algorithms like Bubble Sort and Insertion Sort are typically stable, Quick Sort is often unstable because it swaps elements over long distances.

#include <stdio.h>

struct Student {
    char name[20];
    int grade;
};

// A stable sort (like a careful Bubble Sort) 
// keeps "Alice" before "Bob" if they have the same grade.
void stable_sort_example(struct Student arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            // Using '>' instead of '>=' ensures stability
            if (arr[j].grade > arr[j + 1].grade) {
                struct Student temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

In the code above, by only swapping when one grade is strictly greater than another, we ensure that equals never jump over each other, maintaining the original order.

Key takeaway

A stable sort preserves the original relative order of elements with equal keys, which is essential for complex, multi-layered data sorting.