The user wants a program that performs stable sorting.
"Stable sorting" means that if two elements have the same value (or key), their relative order from the original input is preserved in the sorted output.
I need to decide on a programming language. Python is a good default choice because of its readability and built-in support for stable sorting. I should also mention how to do it in C++ or Java, as they are common languages where stability matters (some standard algorithms are stable, some aren't).
Let's start with Python.
Python's list.sort() and sorted() are guaranteed to be stable.
I should create a custom class or a tuple to demonstrate that the original order is kept when the sorting key is the same.
Example: A list of tuples (name, score).
Sort by score.
If two people have the same score, they should appear in the output in the same order they appeared in the input.
Let's consider a more visual example.
Input: [(3, 'a'), (1, 'b'), (2, 'c'), (1, 'd')]
Sort by the first element.
Output should be: [(1, 'b'), (1, 'd'), (2, 'c'), (3, 'a')]
Notice that (1, 'b') comes before (1, 'd') because 'b' was before 'd' in the original list.
I will write a Python script.
I'll define a class Student with name and grade.
I'll create a list of students with some duplicate grades.
I'll sort them using sorted() with a key lambda.
I'll print the before and after to prove stability.
I should also explain why it's stable (TimSort is used in Python).
What if the user wants to implement a stable sort algorithm from scratch (like Merge Sort) instead of using a built-in function?
The prompt says "Create a program that performs stable sorting". It doesn't explicitly say "implement a sorting algorithm from scratch". Usually, this means "show me how to use the language's features to achieve stable sorting". However, providing an implementation of Merge Sort adds value and educational context.
I will provide two approaches:
Using Python's built-in stable sort (best practice).
Implementing a stable algorithm (Merge Sort) manually to demonstrate the concept.
Let's stick to Python for the primary example as it's the most accessible.
Plan:
Explain what a stable sort is.
Example 1: Python built-in sort (TimSort). Use a list of objects/tuples with duplicate keys.
Example 2: Manual implementation of Merge Sort (a classic stable sort) to show the logic explicitly.
Briefly mention other languages (C++ stable_sort, Java Collections.sort).
Drafting the Python Code (Built-in):
Data: List of dicts {'id': 1, 'value': 'A'}...
Actually, a tuple (score, name) is easier.
List: [(5, 'Alice'), (2, 'Bob'), (5, 'Charlie'), (1, 'David')]
Key to sort: The first element (score).
Expected result: (1, 'David'), (2, 'Bob'), (5, 'Alice'), (5, 'Charlie').
'Alice' must come before 'Charlie'.
Drafting the Python Code (Manual Merge Sort):
Need a function merge_sort(arr).
Base case: len <= 1.
Recursive step: split, sort left, sort right, merge.
The merge step is crucial: if left[i] <= right[j], take left. The <= ensures stability (if equal, prefer the one that came first, which is usually the left side).
Let's refine the prompt interpretation. "Create a program..." usually implies a complete, runnable script.
I will provide the Python solution using the built-in method (as it's the industry standard for "doing" stable sorting) and explain the "manual" way for understanding.
Structure of the response:
Concept explanation.
Code Example 1: Using Python's built-in sorted() (Practical approach).
Code Example 2: Implementing Merge Sort (Educational approach).
Explanation of the code output.
Let's double check C++.
std::sort is not guaranteed to be stable (IntroSort).
std::stable_sort is stable.
I will add a note about this distinction because it's a common interview topic.
Let's write the Python code clearly.
python
# Data with duplicate keys to demonstrate stability
data = [
(3, 'apple'),
(2, 'banana'),
(3, 'cherry'),
(1, 'date'),
(2, 'elderberry')
]
# Sort by the first element (the number)
# Python's sorted() is stable.
sorted_data = sorted(data, key=lambda x: x[0])
This looks good. I will generate the response based on this.
Here is a solution that demonstrates Stable Sorting.
A sorting algorithm is considered "stable" if it preserves the relative order of equal elements. For example, if you have two items with the same score, the one that appeared first in the original list will also appear first in the sorted list.
I will provide two approaches:
The Pythonic Approach: Using Python's built-in sort (which is guaranteed stable).
The Algorithmic Approach: Implementing Merge Sort from scratch (a classic stable algorithm).
Approach 1: Using Python's Built-in Sort
Python’s list.sort() and sorted() functions use Timsort, which is guaranteed to be stable. This is the most efficient way to do it in production code.
python
def demonstrate_stable_sort():
# List of tuples: (Score, Name)
# We want to sort by Score (index 0)
data = [
(85, "Alice"),
(90, "Bob"),
(85, "Charlie"), # Same score as Alice
(70, "David"),
(90, "Eve") # Same score as Bob
]
print("--- Original List ---")
for item in data:
print(item)
# Python's sorted() is stable.
# We sort based on the first element (the score).
# 'key=lambda x: x[0]' tells Python to look at the score.
sorted_data = sorted(data, key=lambda x: x[0])
print("\n--- Stable Sorted List (By Score) ---")
print("Notice that Alice (85) still comes before Charlie (85),")
print("and Bob (90) still comes before Eve (90).")
for item in sorted_data:
print(item)
if __name__ == "__main__":
demonstrate_stable_sort()
Approach 2: Manual Implementation (Merge Sort)
If you need to write the sorting logic yourself (e.g., for a homework assignment or low-level implementation), Merge Sort is the standard choice for stable sorting.
The key to its stability is in the merge step: when comparing two equal elements from the left and right sublists, we prioritize the left one to preserve the original order.
python
def merge_sort(arr):
# Base case: A list of 0 or 1 elements is already sorted
if len(arr) <= 1:
return arr
# Split the list in half
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
# Recursively sort both halves
left_sorted = merge_sort(left_half)
right_sorted = merge_sort(right_half)
# Merge the sorted halves
return merge(left_sorted, right_sorted)
def merge(left, right):
sorted_list = []
i = 0 # Pointer for left list
j = 0 # Pointer for right list
# Compare elements from both lists
while i < len(left) and j < len(right):
# THE KEY TO STABILITY:
# If elements are equal (<=), we pick the one from the LEFT list first.
# This preserves the original relative order.
if left[i][0] <= right[j][0]:
sorted_list.append(left[i])
i += 1
else:
sorted_list.append(right[j])
j += 1
# Append any remaining elements
sorted_list.extend(left[i:])
sorted_list.extend(right[j:])
return sorted_list
# --- Main Execution ---
if __name__ == "__main__":
# Data: (Score, Name)
data = [
(3, "Third"),
(1, "First"),
(2, "Second"),
(1, "First_Again") # Duplicate score
]
print("Original:", data)
# Perform Manual Stable Sort
result = merge_sort(data)
print("Sorted: ", result)
# Expected output: [(1, 'First'), (1, 'First_Again'), (2, 'Second'), (3, 'Third')]
# 'First' comes before 'First_Again' because the sort is stable.