📖 Scenario: You work in a small bookstore that keeps track of books by their title and year of publication. You want to sort the books by year but keep the order of books with the same year as they were originally added. This is called a stable sort. You will learn how to create a list of books, choose a sorting method, and see how stability affects the order.
🎯 Goal: Build a program that stores a list of books with their titles and years, then sorts them by year using a stable sorting method. You will see how the order of books with the same year stays the same after sorting.
📋 What You'll Learn
Create a list of books with exact titles and years
Create a variable to hold the number of books
Use a stable sorting method to sort books by year
Print the sorted list showing title and year
💡 Why This Matters
🌍 Real World
Sorting books or products by attributes like year or price while keeping the original order of items with the same attribute is common in inventory and catalog management.
💼 Career
Understanding stable sorting helps in software development roles involving data processing, UI lists, and any scenario where order preservation matters.
Progress0 / 4 steps
1
Create the list of books
Create a struct Book with title (string) and year (int). Then create a vector<Book> called books with these exact entries: {"The Hobbit", 1937}, {"1984", 1949}, {"Animal Farm", 1945}, {"Brave New World", 1932}, {"Fahrenheit 451", 1953}, {"The Catcher in the Rye", 1951}, {"Lord of the Flies", 1954}, {"The Great Gatsby", 1925}, {"To Kill a Mockingbird", 1960}, {"The Hobbit", 1937} (note the duplicate title with same year).
DSA C++
Hint
Use struct to define Book with title and year. Then create a std::vector<Book> with the exact books listed.
2
Create a variable for the number of books
Create an int variable called n and set it to the size of the books vector using books.size().
DSA C++
Hint
Use int n = books.size(); to get the number of books.
3
Sort the books by year using a stable sort
Use std::stable_sort with a lambda function to sort the books vector by the year field in ascending order. The lambda should take two Book references called a and b and return a.year < b.year.
DSA C++
Hint
Use std::stable_sort with a lambda that compares a.year and b.year.
4
Print the sorted list of books
Use a for loop with variable i from 0 to n - 1 to print each book's title and year in the format: Title: [title], Year: [year].
DSA C++
Hint
Use a for loop from 0 to n - 1 and print each book's title and year with std::cout.
Practice
(1/5)
1. Which of the following sorting algorithms is stable by default?
easy
A. Merge Sort
B. Quick Sort
C. Heap Sort
D. Selection Sort
Solution
Step 1: Understand stability in sorting
A stable sort keeps the relative order of equal elements the same as in the input.
Step 2: Check common sorting algorithms
Merge Sort is stable because it merges sorted halves without changing order of equal elements. Quick Sort, Heap Sort, and Selection Sort are not stable by default.
Final Answer:
Merge Sort -> Option A
Quick Check:
Stable sort = Merge Sort [OK]
Hint: Remember: Merge Sort is stable, Quick Sort is not [OK]
Common Mistakes:
Thinking Quick Sort is stable
Confusing stability with time complexity
Assuming all comparison sorts are stable
2. Which syntax correctly declares a stable sort call on a vector v in C++ STL?
easy
A. v.stable_sort();
B. std::sort(v.begin(), v.end(), stable);
C. std::stable_sort(v.begin(), v.end());
D. std::sort_stable(v.begin(), v.end());
Solution
Step 1: Recall C++ STL stable sort syntax
The function is std::stable_sort with two iterators as arguments.
Step 2: Check options for correctness
std::stable_sort(v.begin(), v.end()); matches correct syntax. Options A, B, and D are invalid or do not exist in STL.
stable_sort sorts by key ascending but keeps relative order of equal keys.
Step 2: Sort vector and trace output
Keys sorted: 1, 2, 2. For key=2, 'a' comes before 'c' in original, so order stays '2a' then '2c'. Output: "1b 2a 2c "
Final Answer:
1b 2a 2c -> Option D
Quick Check:
Stable sort keeps order of equal keys [OK]
Hint: Stable sort keeps original order for equal keys [OK]
Common Mistakes:
Assuming equal keys reorder arbitrarily
Confusing stable_sort with sort
Ignoring the lambda comparator effect
4. Identify the error in this code snippet that tries to use stable sort on an array:
int arr[] = {3, 1, 2};
std::stable_sort(arr, arr + 3);
for (int i = 0; i < 3; i++) std::cout << arr[i] << ' ';
medium
A. No error; code runs correctly
B. Array pointers used incorrectly in stable_sort
C. stable_sort cannot be used on arrays
D. Missing comparator function causes error
Solution
Step 1: Check stable_sort usage on arrays
std::stable_sort accepts pointers as iterators, so arr and arr+3 are valid.
Step 2: Verify code correctness
Code sorts array {3,1,2} to {1,2,3} and prints correctly. No error present.
Final Answer:
No error; code runs correctly -> Option A
Quick Check:
stable_sort works with array pointers [OK]
Hint: stable_sort works with pointers, no comparator needed for default order [OK]
Common Mistakes:
Thinking stable_sort needs vector only
Assuming comparator is mandatory
Confusing pointers with iterators
5. You have a list of employees with fields name and age. You want to sort them by age but keep the original order for employees with the same age. Which sorting algorithm should you use and why?
hard
A. Heap Sort, because it uses less memory
B. Stable Sort (like Merge Sort), to preserve order of equal ages
C. Quick Sort, because it is faster on average
D. Selection Sort, because it is simple to implement
Solution
Step 1: Understand requirement for stability
We want to keep original order for employees with same age, so sorting must be stable.
Step 2: Choose sorting algorithm based on stability
Merge Sort or any stable sort preserves order of equal keys. Quick Sort, Heap Sort, Selection Sort are not stable by default.
Final Answer:
Stable Sort (like Merge Sort), to preserve order of equal ages -> Option B
Quick Check:
Stable sort needed to keep order [OK]
Hint: Use stable sort to keep order of equal keys [OK]
Common Mistakes:
Choosing faster but unstable sorts
Ignoring stability requirement
Confusing simplicity with correctness
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.