0
0
DSA Javascriptprogramming~30 mins

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

Choose your learning style9 modes available
Sorting Stability and When to Use Which Sort
📖 Scenario: You work at a bookstore that keeps a list of books with their titles and prices. Sometimes, books have the same price. You want to sort the books by price but keep the order of books with the same price as they were originally. This is called a stable sort.Later, you want to understand when to use different sorting methods based on speed and stability.
🎯 Goal: You will create a list of books, add a sorting preference, sort the books by price using a stable sort, and then print the sorted list showing how stable sorting keeps the original order for books with the same price.
📋 What You'll Learn
Create an array of book objects with exact titles and prices
Add a variable to choose sorting method
Use a stable sorting method to sort books by price
Print the sorted list showing title and price
💡 Why This Matters
🌍 Real World
Sorting lists of products, books, or any items by price or other attributes is common in online stores and inventory systems. Stable sorting helps keep the original order when items have the same key, which can be important for user experience.
💼 Career
Understanding sorting stability and when to use stable or unstable sorts is important for software developers working on data processing, UI lists, and performance optimization.
Progress0 / 4 steps
1
Create the list of books
Create an array called books with these exact objects in this order: { title: 'Book A', price: 30 }, { title: 'Book B', price: 20 }, { title: 'Book C', price: 30 }, { title: 'Book D', price: 10 }
DSA Javascript
Hint

Use const books = [ ... ] with objects inside curly braces.

2
Add sorting method choice
Create a variable called useStableSort and set it to true to choose stable sorting
DSA Javascript
Hint

Use const useStableSort = true; to set the sorting method.

3
Sort the books by price using stable sort
Use books.sort() with a compare function that compares a.price and b.price to sort the books by price in ascending order. Use the variable useStableSort to decide if sorting should happen.
DSA Javascript
Hint

Use books.sort((a, b) => a.price - b.price) to sort by price ascending.

4
Print the sorted list of books
Use a for loop with variables book to go through books and print each book's title and price in the format Title: Book A, Price: 30
DSA Javascript
Hint

Use for (const book of books) and console.log with template strings.