Consider the list of tuples representing (name, score):
[('Alice', 90), ('Bob', 85), ('Charlie', 90), ('David', 85)]If we sort this list by score using a stable sorting algorithm, what will be the order of elements after sorting?
data = [('Alice', 90), ('Bob', 85), ('Charlie', 90), ('David', 85)] sorted_data = sorted(data, key=lambda x: x[1]) print(sorted_data)
Remember that stable sort keeps the original order of equal elements.
Stable sort keeps the relative order of elements with equal keys. Here, 'Bob' and 'David' both have score 85, and 'Bob' comes before 'David' originally, so 'Bob' stays before 'David' after sorting.
Among the following sorting algorithms, which one is stable by default?
Think about which algorithm merges sorted sublists without changing order of equal elements.
Merge Sort is stable because it merges sorted lists by comparing elements and preserving their order when equal.
Given the list of objects with duplicate keys, what is the output after sorting with an unstable algorithm?
data = [{'id': 1, 'value': 10}, {'id': 2, 'value': 5}, {'id': 3, 'value': 10}, {'id': 4, 'value': 5}]
# Sort by 'value' using an unstable sortdata = [{'id': 1, 'value': 10}, {'id': 2, 'value': 5}, {'id': 3, 'value': 10}, {'id': 4, 'value': 5}]
# Simulate unstable sort by sorting with a custom unstable method
# For demonstration, we use sorted but shuffle equal elements manually
sorted_data = sorted(data, key=lambda x: x['value'])
# Manually swap equal elements to simulate instability
sorted_data[0], sorted_data[1] = sorted_data[1], sorted_data[0]
print(sorted_data)Look at the order of elements with the same 'value' after swapping.
After swapping the first two elements with value 5, the order is changed, showing instability. The output matches option D.
You have a very large dataset that cannot fit entirely into memory. You need to sort it efficiently. Which sorting algorithm is best suited for this scenario?
Consider external sorting and how the algorithm handles data in chunks.
Merge Sort is suitable for external sorting because it can sort data in chunks and merge them efficiently, even when data doesn't fit in memory.
When sorting data by multiple keys (like first by age, then by name), why is it important to use a stable sorting algorithm?
Think about sorting by one key, then sorting again by another key without losing previous order.
Stable sort preserves the order of equal elements, so when sorting by the second key, the order from the first key remains intact, enabling correct multi-level sorting.
