0
0
DSA Goprogramming~30 mins

Sorting Stability and When to Use Which Sort in DSA Go - Build from Scratch

Choose your learning style9 modes available
Sorting Stability and When to Use Which Sort
📖 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.