GO / CHAPTER 07

Sorting, searching, and stable ties

Intermediate

Establish ordering before depending on search results.

By the end of this chapter

  • State binary-search preconditions
  • Trace a lower-bound search
  • Define deterministic tie behavior

The idea

Sorting establishes an order that later algorithms can rely on. A comparison function should express a consistent strict ordering; using less-than-or-equal for equal elements breaks that contract. Decide whether equal keys should retain their previous order or be ordered by a secondary field. A stable sort preserves their earlier order, while an explicit secondary key makes a different policy visible.

A lower-bound search finds the first position where a monotonic predicate becomes true. For sorted numbers, searching for the first value at least a target gives either a candidate index or the length when no candidate exists. Check the returned boundary before indexing, then compare for equality if you need an exact match. Searching an unsorted slice violates the required monotonicity.

Go example
package main
import ("fmt"; "sort")
func main(){ xs:=[]int{8,2,5,5}; sort.Ints(xs); i:=sort.SearchInts(xs,5); fmt.Println(xs); fmt.Println(i) }
Result
[2 5 5 8]
1

SearchInts returns the first insertion position for five, which is the first matching index here.

Try it yourself

Find whether a sorted slice contains a target without panicking for an empty slice.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

For sorted [2,5,5,8], what is the first index whose value is at least six?