0
0
DSA Goprogramming~20 mins

Sorting Stability and When to Use Which Sort in DSA Go - Practice Problems & Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Sorting Stability Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this stable sort on a list of structs?

Given a list of structs with fields value and id, a stable sort is applied by value. What is the order of id after sorting?

DSA Go
package main

import (
	"fmt"
	"sort"
)

type item struct {
	value int
	id    int
}

func main() {
	items := []item{{3, 1}, {1, 2}, {3, 3}, {2, 4}}
	sort.SliceStable(items, func(i, j int) bool {
		return items[i].value < items[j].value
	})
	for _, it := range items {
		fmt.Print(it.id, " ")
	}
}
A2 4 3 1
B1 3 4 2
C4 2 1 3
D2 4 1 3
Attempts:
2 left
💡 Hint

Stable sort keeps the original order of equal elements.

🧠 Conceptual
intermediate
1:30remaining
Which sorting algorithm is stable by default?

Choose the sorting algorithm that is stable by default without extra modifications.

AMerge Sort
BSelection Sort
CHeap Sort
DQuick Sort
Attempts:
2 left
💡 Hint

Think about which algorithm merges sorted lists preserving order.

🚀 Application
advanced
1:30remaining
When should you prefer an unstable sort over a stable sort?

Choose the best scenario to prefer an unstable sort algorithm.

AWhen memory usage must be minimal and speed is critical
BWhen sorting linked lists where stability is guaranteed
CWhen you need to preserve the relative order of equal elements
DWhen sorting small arrays where stability is required
Attempts:
2 left
💡 Hint

Unstable sorts often use less memory and can be faster.

🔧 Debug
advanced
2:00remaining
What error occurs in this Go code using sort.Slice instead of sort.SliceStable?

What is the output or error of this code that sorts a slice of structs by value but uses sort.Slice instead of sort.SliceStable?

DSA Go
package main

import (
	"fmt"
	"sort"
)

type item struct {
	value int
	id    int
}

func main() {
	items := []item{{3, 1}, {1, 2}, {3, 3}, {2, 4}}
	sort.Slice(items, func(i, j int) bool {
		return items[i].value < items[j].value
	})
	for _, it := range items {
		fmt.Print(it.id, " ")
	}
}
A2 4 1 3
B2 4 3 1
CCompilation error
DRuntime panic
Attempts:
2 left
💡 Hint

sort.Slice is not stable, so equal elements may reorder.

🧠 Conceptual
expert
2:00remaining
Why is stability important in multi-level sorting?

Choose the best explanation why stable sorting is crucial when sorting by multiple keys in sequence.

AIt guarantees the fastest sorting time for large datasets
BIt reduces the total number of comparisons needed
CIt preserves the order of previous sorts when sorting by the next key
DIt allows sorting in place without extra memory
Attempts:
2 left
💡 Hint

Think about sorting by one key, then sorting again by another key without losing the first order.