Bird
Raised Fist0
DSA Pythonprogramming~3 mins

Why Sorting Stability and When to Use Which Sort in DSA Python?

Choose your learning style10 modes available
The Big Idea

What if sorting could keep your data's story intact instead of mixing it up?

The Scenario

Imagine you have a list of students with their names and scores. You want to sort them by score but keep the original order for students with the same score. Doing this by hand means checking each pair carefully and rewriting the list again and again.

The Problem

Manually sorting is slow and easy to mess up. You might accidentally change the order of students with the same score, losing important information. It's hard to keep track of who came first when scores are equal.

The Solution

Sorting stability means when two items have the same value, their order stays the same after sorting. Using stable sorting algorithms, you can sort by one property and then by another without losing the original order. This saves time and keeps data organized.

Before vs After
✗ Before
students = [("Alice", 90), ("Bob", 90), ("Charlie", 85)]
# Unstable selection sort example:
for i in range(len(students)):
    min_idx = i
    for j in range(i+1, len(students)):
        if students[j][1] < students[min_idx][1]:
            min_idx = j
    students[i], students[min_idx] = students[min_idx], students[i]
# Results in Charlie, Alice, Bob -- reorders equal scores
✓ After
students = [("Alice", 90), ("Bob", 90), ("Charlie", 85)]
students.sort(key=lambda x: x[1])  # Keeps Alice before Bob
What It Enables

Stable sorting lets you sort complex data step-by-step without losing the original order of equal items, making your data clearer and easier to work with.

Real Life Example

When sorting a list of job applicants first by experience and then by name, stable sorting keeps applicants with the same experience in alphabetical order, helping recruiters fairly compare candidates.

Key Takeaways

Manual sorting is slow and error-prone for equal values.

Stable sorting keeps the order of equal items unchanged.

Choosing the right sort helps keep data organized and meaningful.

Practice

(1/5)
1. What does it mean when a sorting algorithm is called stable?
easy
A. It keeps the original order of equal elements unchanged.
B. It sorts the elements in ascending order only.
C. It uses less memory than unstable sorts.
D. It always sorts in place without extra space.

Solution

  1. Step 1: Understand stability in sorting

    A stable sort keeps elements with the same value in the same order as they appeared originally.
  2. Step 2: Compare options with definition

    Only It keeps the original order of equal elements unchanged. describes this property correctly. Other options describe different concepts.
  3. Final Answer:

    It keeps the original order of equal elements unchanged. -> Option A
  4. Quick Check:

    Stable sort = keeps order of equal elements [OK]
Hint: Stable means equal items keep their original order [OK]
Common Mistakes:
  • Confusing stability with sorting order
  • Thinking stability means less memory use
  • Assuming all sorts are stable
2. Which of the following Python sorting methods is stable by default?
easy
A. sorted() function
B. list.sort() method
C. Neither sorted() nor list.sort()
D. Both sorted() and list.sort()

Solution

  1. Step 1: Recall Python sorting stability

    Both sorted() and list.sort() use Timsort, which is stable.
  2. Step 2: Check options

    Options A and B are each correct alone, but Both sorted() and list.sort() correctly states both are stable.
  3. Final Answer:

    Both sorted() and list.sort() -> Option D
  4. Quick Check:

    Python sorts are stable by default [OK]
Hint: Python's built-in sorts are stable by default [OK]
Common Mistakes:
  • Thinking only one method is stable
  • Confusing stability with sorting order
  • Assuming custom sorts are stable by default
3. Consider this list of tuples representing (name, score):
data = [("Alice", 90), ("Bob", 90), ("Charlie", 85)]
What will be the output after sorting by score using sorted(data, key=lambda x: x[1])?
medium
A. [('Charlie', 85), ('Bob', 90), ('Alice', 90)]
B. [('Alice', 90), ('Bob', 90), ('Charlie', 85)]
C. [('Charlie', 85), ('Alice', 90), ('Bob', 90)]
D. [('Bob', 90), ('Alice', 90), ('Charlie', 85)]

Solution

  1. Step 1: Understand sorting by score

    The sort uses the second item (score) as key, sorting ascending: 85, 90, 90.
  2. Step 2: Check stability for equal scores

    Since Python's sort is stable, 'Alice' and 'Bob' keep their original order for score 90.
  3. Final Answer:

    [('Charlie', 85), ('Alice', 90), ('Bob', 90)] -> Option C
  4. Quick Check:

    Stable sort keeps 'Alice' before 'Bob' [OK]
Hint: Stable sort keeps original order for equal keys [OK]
Common Mistakes:
  • Swapping order of equal elements
  • Sorting descending by mistake
  • Ignoring stability property
4. You wrote this code to sort a list of dictionaries by 'age':
people = [{'name': 'Ann', 'age': 25}, {'name': 'Ben', 'age': 20}, {'name': 'Cara', 'age': 25}]
people.sort(key=lambda x: x['age'])
print(people)

But the output does not keep the original order of people with the same age. What is the likely cause?
medium
A. The key function is incorrect.
B. The dictionaries are unordered, causing instability.
C. The list.sort() method is stable, so no cause.
D. The sort method used is unstable.

Solution

  1. Step 1: Recall Python sort stability

    Python's list.sort() is stable, so it keeps order of equal keys.
  2. Step 2: Understand dictionary order

    Before Python 3.7, dictionaries did not preserve insertion order, so printing may show different order.
  3. Step 3: Identify cause

    If using older Python or unordered dicts, the printed order may seem unstable even if sort is stable.
  4. Final Answer:

    The dictionaries are unordered, causing instability. -> Option B
  5. Quick Check:

    Unordered dicts can hide stable sort [OK]
Hint: Unordered dicts can hide stable sort effects [OK]
Common Mistakes:
  • Blaming sort method instead of dict order
  • Changing key function unnecessarily
  • Ignoring Python version differences
5. You have a list of student records with (name, grade, age). You want to sort by grade ascending, then by age descending, but keep the original order for students with same grade and age. Which sorting approach is best?
hard
A. Use a stable sort twice: first by age descending, then by grade ascending.
B. Use an unstable sort once with a combined key (grade, -age).
C. Use a stable sort once with key (grade, age).
D. Sort by age ascending, then by grade descending using stable sorts.

Solution

  1. Step 1: Understand multi-level sorting with stability

    To sort by multiple keys and keep original order for ties, use stable sorts starting from the last key.
  2. Step 2: Apply sorting order

    First sort by age descending (second key), then by grade ascending (first key), both stable.
  3. Step 3: Check options

    Use a stable sort twice: first by age descending, then by grade ascending. matches this approach. Others either use unstable sort or wrong key order.
  4. Final Answer:

    Use a stable sort twice: first by age descending, then by grade ascending. -> Option A
  5. Quick Check:

    Stable sorts chained preserve multi-key order [OK]
Hint: Sort by last key first with stable sort, then first key [OK]
Common Mistakes:
  • Sorting keys in wrong order
  • Using unstable sort for multi-key sorting
  • Ignoring descending order for age
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard