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?
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, " ") } }
Stable sort keeps the original order of equal elements.
The stable sort orders by value: 1, 2, 3, 3. For equal values (3 and 3), the original order of id 1 then 3 is preserved.
Choose the sorting algorithm that is stable by default without extra modifications.
Think about which algorithm merges sorted lists preserving order.
Merge Sort is stable because it merges two sorted halves by comparing elements and preserving their original order when equal.
Choose the best scenario to prefer an unstable sort algorithm.
Unstable sorts often use less memory and can be faster.
Unstable sorts like Quick Sort or Heap Sort often use less memory and can be faster, so prefer them when stability is not needed but speed and memory are important.
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?
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, " ") } }
sort.Slice is not stable, so equal elements may reorder.
sort.Slice sorts but is not stable, so the two items with value 3 may swap order. The output is 2 4 3 1 instead of 2 4 1 3.
Choose the best explanation why stable sorting is crucial when sorting by multiple keys in sequence.
Think about sorting by one key, then sorting again by another key without losing the first order.
Stable sorting preserves the order of equal elements, so when sorting by multiple keys, the previous key's order is kept intact after sorting by the next key.