0
0
DSA C++programming

Sorting Stability and When to Use Which Sort in DSA C++

Choose your learning style9 modes available
Mental Model
Stable sorting keeps equal items in the same order they started. Different sorts work best for different situations.
Analogy: Imagine sorting playing cards by number but keeping the order of cards with the same number as they were originally dealt.
Unsorted list:
5a -> 3 -> 5b -> 2 -> 3 -> null

Stable sort keeps 5a before 5b and the first 3 before the second 3.
Dry Run Walkthrough
Input: list: 5a -> 3 -> 5b -> 2 -> 3, stable sort by number ascending
Goal: Sort the list by number ascending while keeping the order of equal numbers the same
Step 1: compare 5a and 3, 3 is smaller so move 3 before 5a
3 -> 5a -> 5b -> 2 -> 3 -> null
Why: We want smaller numbers first
Step 2: compare 5a and 5b, both 5 so keep 5a before 5b
3 -> 5a -> 5b -> 2 -> 3 -> null
Why: Stable sort keeps original order of equal elements
Step 3: compare 5b and 2, 2 is smaller so move 2 before 5b
3 -> 5a -> 2 -> 5b -> 3 -> null
Why: Smaller number 2 should come before 5b
Step 4: compare 3 and 2, 2 is smaller so move 2 before 3
2 -> 3 -> 5a -> 5b -> 3 -> null
Why: 2 is smallest so it goes first
Step 5: compare last 3 with previous 3, keep order same
2 -> 3 -> 3 -> 5a -> 5b -> null
Why: Stable sort keeps equal elements in original order
Result:
2 -> 3 -> 3 -> 5a -> 5b -> null
Annotated Code
DSA C++
#include <iostream>
#include <vector>
#include <string>

struct Card {
    int number;
    char id; // to distinguish duplicates
};

// Stable insertion sort for demonstration
void stableInsertionSort(std::vector<Card>& cards) {
    for (int i = 1; i < (int)cards.size(); i++) {
        Card key = cards[i];
        int j = i - 1;
        // Move elements greater than key.number one position ahead
        while (j >= 0 && cards[j].number > key.number) {
            cards[j + 1] = cards[j];
            j--;
        }
        cards[j + 1] = key; // Insert key at correct position
    }
}

void printCards(const std::vector<Card>& cards) {
    for (const auto& c : cards) {
        std::cout << c.number << c.id << " -> ";
    }
    std::cout << "null" << std::endl;
}

int main() {
    std::vector<Card> cards = {{5, 'a'}, {3, ' '}, {5, 'b'}, {2, ' '}, {3, ' '}};
    std::cout << "Before sorting:" << std::endl;
    printCards(cards);
    stableInsertionSort(cards);
    std::cout << "After stable sorting by number ascending:" << std::endl;
    printCards(cards);
    return 0;
}
for (int i = 1; i < (int)cards.size(); i++) {
iterate over cards starting from second element
while (j >= 0 && cards[j].number > key.number) {
shift cards greater than key to the right
cards[j + 1] = key;
insert key at correct sorted position
OutputSuccess
Before sorting: 5a -> 3 -> 5b -> 2 -> 3 -> null After stable sorting by number ascending: 2 -> 3 -> 3 -> 5a -> 5b -> null
Complexity Analysis
Time: O(n^2) because insertion sort compares and shifts elements in worst case
Space: O(1) because sorting is done in place without extra storage
vs Alternative: Stable sorts like insertion or merge keep order of equal elements, unlike quicksort which is usually unstable but faster O(n log n)
Edge Cases
empty list
no sorting needed, list remains empty
DSA C++
for (int i = 1; i < (int)cards.size(); i++) {
list with all equal elements
order remains same because stable sort preserves order
DSA C++
while (j >= 0 && cards[j].number > key.number) {
list with one element
no sorting needed, list remains same
DSA C++
for (int i = 1; i < (int)cards.size(); i++) {
When to Use This Pattern
When you need to keep the original order of equal elements after sorting, look for a stable sort like insertion or merge sort.
Common Mistakes
Mistake: Using an unstable sort when order of equal elements matters
Fix: Choose a stable sorting algorithm or modify the sort to preserve order
Mistake: Assuming all sorts are stable by default
Fix: Check the algorithm's stability property before using it
Summary
Stable sorting keeps equal elements in their original order after sorting.
Use stable sorts when the order of equal items matters, like sorting cards or records with multiple keys.
The key insight is that stable sorts never reorder equal elements, preserving their initial sequence.