What if sorting could keep your data's story intact instead of mixing it up?
Why Sorting Stability and When to Use Which Sort in DSA Python?
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.
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.
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.
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
students = [("Alice", 90), ("Bob", 90), ("Charlie", 85)] students.sort(key=lambda x: x[1]) # Keeps Alice before Bob
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.
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.
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
stable?Solution
Step 1: Understand stability in sorting
A stable sort keeps elements with the same value in the same order as they appeared originally.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.Final Answer:
It keeps the original order of equal elements unchanged. -> Option AQuick Check:
Stable sort = keeps order of equal elements [OK]
- Confusing stability with sorting order
- Thinking stability means less memory use
- Assuming all sorts are stable
Solution
Step 1: Recall Python sorting stability
Bothsorted()andlist.sort()use Timsort, which is stable.Step 2: Check options
Options A and B are each correct alone, but Both sorted() and list.sort() correctly states both are stable.Final Answer:
Both sorted() and list.sort() -> Option DQuick Check:
Python sorts are stable by default [OK]
- Thinking only one method is stable
- Confusing stability with sorting order
- Assuming custom sorts are stable by default
data = [("Alice", 90), ("Bob", 90), ("Charlie", 85)]What will be the output after sorting by score using sorted(data, key=lambda x: x[1])?Solution
Step 1: Understand sorting by score
The sort uses the second item (score) as key, sorting ascending: 85, 90, 90.Step 2: Check stability for equal scores
Since Python's sort is stable, 'Alice' and 'Bob' keep their original order for score 90.Final Answer:
[('Charlie', 85), ('Alice', 90), ('Bob', 90)] -> Option CQuick Check:
Stable sort keeps 'Alice' before 'Bob' [OK]
- Swapping order of equal elements
- Sorting descending by mistake
- Ignoring stability property
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?
Solution
Step 1: Recall Python sort stability
Python'slist.sort()is stable, so it keeps order of equal keys.Step 2: Understand dictionary order
Before Python 3.7, dictionaries did not preserve insertion order, so printing may show different order.Step 3: Identify cause
If using older Python or unordered dicts, the printed order may seem unstable even if sort is stable.Final Answer:
The dictionaries are unordered, causing instability. -> Option BQuick Check:
Unordered dicts can hide stable sort [OK]
- Blaming sort method instead of dict order
- Changing key function unnecessarily
- Ignoring Python version differences
(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?Solution
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.Step 2: Apply sorting order
First sort by age descending (second key), then by grade ascending (first key), both stable.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.Final Answer:
Use a stable sort twice: first by age descending, then by grade ascending. -> Option AQuick Check:
Stable sorts chained preserve multi-key order [OK]
- Sorting keys in wrong order
- Using unstable sort for multi-key sorting
- Ignoring descending order for age
Ready to prove it?
Pass the test and this pattern moves unknown
