The user wants a program that performs a stable sort.
Key requirement: "maintains element order" (meaning the relative order of equal elements must be preserved).
I need to choose a language. Python is a good choice for readability and demonstration, as its built-in sort (Timsort) is stable. However, implementing a specific stable sorting algorithm (like Merge Sort) from scratch is usually what is expected in a programming context when asked to "create a program" for a specific type of sort, rather than just calling .sort().
So, I will provide:
- A custom implementation of Merge Sort (the classic stable sort algorithm).
- An example demonstrating the stability (sorting objects with multiple fields, where one field determines the sort order and the other helps visualize stability).
Let's plan the Python code:
- Class
Item to hold data (e.g., name, age).
merge_sort function.
- Base case: list length <= 1.
- Recursive step: split, sort left, sort right, merge.
- Merge step needs to be careful: if
left[i] <= right[j], take left. Using <= is crucial for stability (if equal, take the one from the left half, which appeared earlier).
- Main execution block to test it.
Alternative languages: C++, Java.
In C++, std::stable_sort exists, but again, writing the logic is often the intent. Python is most accessible.
Let's refine the Merge Sort logic for stability.
During the merge process:
If left[i] is equal to right[j], we must pick left[i] first.
Standard merge sort does this naturally if written as if left[i] <= right[j].
Let's double-check the prompt. "Create a program that performs stable sorting and maintains element order."
This could also just mean "Show me how to use a stable sort in Python."
I will provide the custom implementation (Merge Sort) because it's more educational and demonstrates the mechanism, but I'll also mention that Python's built-in sort is stable.
Let's write the code mentally.
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return f"{self.name} (Grade: {self.grade}, Age: {self.age})"
def merge_sort(arr, key=lambda x: x):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid], key)
right = merge_sort(arr[mid:], key)
return merge(left, right, key)
def merge(left, right, key):
result = []
i = j = 0
while i < len(left) and j < len(right):
# Crucial for stability: if equal, pick left first
if key(left[i]) <= key(right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
This looks correct.
I should probably provide a clearer example.
Input:
(“Alice”, A, 20)
(“Bob”, B, 19)
(“Charlie”, A, 21)
(“David”, B, 22)
Sort by Grade.
Expected Stable Output:
(“Alice”, A, 20)
(“Charlie”, A, 21)
(“Bob”, B, 19)
(“David”, B, 22)
If the sort wasn't stable, Charlie might appear before Alice, or David before Bob.
I will present the solution in Python as it's pseudocode-friendly. I will implement Merge Sort, as it is the standard algorithm used for stable sorting.
Structure of the response:
- Explanation of Stability.
- Code implementation (Merge Sort).
- Demonstration with data objects to prove stability.
Here is a program in Python that implements Merge Sort.
Merge Sort is the standard choice for a stable sorting algorithm. It guarantees O(nlogn) time complexity and, crucially, maintains the relative order of elements that have equal value.
The Python Program
def stable_merge_sort(arr, key=None):
"""
Performs a stable sort using the Merge Sort algorithm.
Args:
arr: The list to sort.
key: A function that extracts a comparison key from each element
(similar to Python's built-in sorted() function).
Returns:
A new list containing the sorted elements.
"""
if len(arr) <= 1:
return arr
# Divide the array into two halves
mid = len(arr) // 2
left_half = stable_merge_sort(arr[:mid], key)
right_half = stable_merge_sort(arr[mid:], key)
return _merge(left_half, right_half, key)
def _merge(left, right, key):
"""
Helper function to merge two sorted lists while maintaining stability.
"""
sorted_list = []
i = 0
j = 0
# Prepare key extraction logic
get_val = key if key else lambda x: x
while i < len(left) and j < len(right):
# Compare keys
# Note the use of <= is crucial here for stability.
# If values are equal, we pick the element from the 'left' list
# because it appeared originally before the 'right' element.
if get_val(left[i]) <= get_val(right[j]):
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
# --- Demonstration ---
class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return f"({self.name}, Grade:{self.grade}, Age:{self.age})"
# 1. Create sample data
# Notice that 'Grade 2' appears multiple times with different names/ages.
students = [
Student("Alice", 2, 12),
Student("Bob", 1, 11),
Student("Charlie", 2, 13),
Student("Diana", 1, 10),
Student("Eve", 3, 14),
]
print("Original List:")
for s in students:
print(s)
# 2. Sort by Grade (Primary Key)
# We expect Bob(Diana to come before Alice/Charlie because 1 < 2.
# We expect Alice to come before Charlie because Alice was originally before Charlie.
sorted_students = stable_merge_sort(students, key=lambda s: s.grade)
print("\nStable Sorted List (by Grade):")
for s in sorted_students:
print(s)
# Verification logic
print("\n--- Verification ---")
# Check specifically if the order of 'Alice' and 'Charlie' (both Grade 2) was kept.
grade_2_students = [s.name for s in sorted_students if s.grade == 2]
if grade_2_students == ['Alice', 'Charlie']:
print("Success: Relative order of elements with Grade 2 was maintained.")
else:
print("Failure: Order was disturbed.")
How it works
- Divide: The list is recursively split into halves until only single elements remain.
- Conquer (Merge): The elements are merged back together in sorted order.
- Stability Check: During the merge step (
_merge function), we compare the values of the left and right sub-lists.
- If
left_value <= right_value, we add the left item to the result first.
- This strict inequality check (
<=) ensures that if two items are equal, the one that appeared earlier (in the left list) is placed into the final list first, preserving the original order.