📖 Scenario: You work in a small bookstore. You have a list of books with their titles and prices. You want to sort the books by price but keep the original order of books with the same price.This helps you keep the order in which books arrived while sorting by price.
🎯 Goal: You will create a list of books, set a price threshold, sort the books by price using a stable sort, and then print the sorted list showing the order is kept for books with the same price.
📋 What You'll Learn
Create a list called books with these exact entries: {Title: "Book A", Price: 30}, {Title: "Book B", Price: 20}, {Title: "Book C", Price: 30}, {Title: "Book D", Price: 10}
Create an integer variable called priceThreshold and set it to 25
Use Go's sort.SliceStable to sort books by Price in ascending order
Print the sorted list in the format: Title: <Title>, Price: <Price> for each book
💡 Why This Matters
🌍 Real World
Sorting products or items by price or rating while keeping the order of items with the same value is common in e-commerce and inventory management.
💼 Career
Understanding stable sorting helps in data processing roles where order preservation is important, such as in databases, UI lists, and report generation.
Progress0 / 4 steps
1
Create the list of books
Create a slice of structs called books with these exact entries: {Title: "Book A", Price: 30}, {Title: "Book B", Price: 20}, {Title: "Book C", Price: 30}, {Title: "Book D", Price: 10}. Define a struct type Book with fields Title string and Price int.
DSA Go
Hint
Define a struct Book with Title and Price. Then create a slice books with the given entries.
2
Set the price threshold
Create an integer variable called priceThreshold and set it to 25 inside the main function, after the books slice.
DSA Go
Hint
Just create a variable priceThreshold and set it to 25.
3
Sort the books by price using stable sort
Use sort.SliceStable to sort the books slice by the Price field in ascending order inside the main function. Import the sort package.
DSA Go
Hint
Use sort.SliceStable(books, func(i, j int) bool { return books[i].Price < books[j].Price }) to sort by price.
4
Print the sorted list of books
Use a for loop to print each book in books in the format: Title: <Title>, Price: <Price> inside the main function.
DSA Go
Hint
Use a for loop with range to print each book's title and price using fmt.Printf.
Practice
(1/5)
1. What does it mean when a sorting algorithm is called stable?
easy
A. It keeps the original order of equal elements after sorting
B. It sorts elements faster than any other algorithm
C. It uses less memory than unstable sorts
D. It only works on numbers, not strings
Solution
Step 1: Understand stability in sorting
A stable sort keeps the relative order of items that compare equal the same as before sorting.
Step 2: Compare options
Only It keeps the original order of equal elements after sorting describes this property correctly. Other options describe speed, memory, or data type restrictions, which are unrelated to stability.
Final Answer:
It keeps the original order of equal elements after sorting -> Option A
Quick Check:
Stable sort = keeps equal items order [OK]
Hint: Stable means equal items keep their original order [OK]
Common Mistakes:
Confusing stability with speed
Thinking stability means less memory use
Believing stability depends on data type
2. Which of the following Go code snippets correctly uses the sort.SliceStable function to sort a slice of structs by an integer field Age?
Hint: Use SliceStable with less-than for ascending stable sort [OK]
Common Mistakes:
Using sort.Slice instead of sort.SliceStable
Reversing comparison for ascending order
Mixing stable and unstable sort functions
3. Given the following Go code, what will be the output after sorting?
type Item struct {
Name string
Rank int
}
items := []Item{{"A", 2}, {"B", 1}, {"C", 2}}
sort.Slice(items, func(i, j int) bool { return items[i].Rank < items[j].Rank })
for _, item := range items {
fmt.Print(item.Name, " ")
}
medium
A. A C B
B. B A C
C. B C A
D. C A B
Solution
Step 1: Understand sorting criteria
The slice is sorted by Rank ascending using sort.Slice, which is unstable.
Step 2: Analyze order of equal Rank elements
Items with Rank 2 are "A" and "C". Since sort.Slice is unstable, their relative order may change. The output shows "B" first (Rank 1), then "C", then "A".
A. Using sort.Slice instead of sort.SliceStable causes unstable sort
B. The comparison function should use > instead of <
C. The slice must be converted to []struct before sorting
D. The code is correct and stable by default
Solution
Step 1: Identify sorting function used
The code uses sort.Slice, which is unstable.
Step 2: Understand stability requirement
To sort stably by length, sort.SliceStable must be used instead.
Final Answer:
Using sort.Slice instead of sort.SliceStable causes unstable sort -> Option A
Quick Check:
Stable sort requires SliceStable, not Slice [OK]
Hint: Use SliceStable for stable sorting, not Slice [OK]
Common Mistakes:
Thinking comparison direction affects stability
Believing slice type conversion is needed
Assuming sort.Slice is stable
5. You have a list of employees with fields Name and Department. You want to sort them first by Department alphabetically and then by Name alphabetically within each department, preserving the order of employees with the same name. Which sorting approach is best in Go?
hard
A. Use one unstable sort by Department only
B. Use two stable sorts: first by Name, then by Department
C. Use one stable sort by concatenated Department+Name string
D. Use two unstable sorts: first by Department, then by Name
Solution
Step 1: Understand multi-level sorting with stability
To sort by Department then Name, stable sorts allow sorting by the secondary key first, then primary key.
Step 2: Apply stable sorts in correct order
Sort first by Name (secondary key) stably, then by Department (primary key) stably. This preserves Name order within Departments.
Final Answer:
Use two stable sorts: first by Name, then by Department -> Option B
Quick Check:
Two stable sorts in reverse order = correct multi-level sort [OK]
Hint: Sort by secondary key first, then primary key with stable sorts [OK]
Common Mistakes:
Using unstable sorts causing order loss
Sorting primary key first losing secondary order
Trying one sort on combined keys without stability
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.