Search linear and sorted collections
Search linear and sorted collections
Linear search scans elements until a match and works on unsorted data. Binary search repeatedly halves a sorted search interval, requiring a consistent order. Use it when the input is already sorted or the cost of sorting can be amortized over many searches.
package main
import ( "fmt")
func find(xs []int, target int) int { for i, x := range xs { if x == target { return i } } return -1}func main() { fmt.Println(find([]int{8, 3, 3}, 3), find(nil, 3))}The first match is returned; -1 means absent. Worst-case time O(n), auxiliary space O(1). The scan checks each earlier element, so it cannot skip a possible match.
Expected output:
1 -1Find the lower bound
package main
import ( "fmt")
func lower(xs []int, t int) int { lo, hi := 0, len(xs) for lo < hi { mid := lo + (hi-lo)/2 if xs[mid] < t { lo = mid + 1 } else { hi = mid } } return lo}func main() { xs := []int{1, 3, 3, 8} i := lower(xs, 3) fmt.Println(i, i < len(xs) && xs[i] == 3) fmt.Println(lower(xs, 9))}The half-open interval [lo,hi) holds unresolved indices; all earlier values are smaller than t and all values at or after hi are at least t. The returned insertion position can equal len(xs). Test bounds before indexing. O(log n) comparisons, constant auxiliary space. Unsorted data invalidates the invariant.
Expected output:
1 true4Try it locally
Use slices.BinarySearch on sorted []int{2,4,4,9} for targets 4 and 5; print insertion index and found flag.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 02: Search linear and sorted collections
Check the lesson objective before moving on.
What does lower bound return for a target larger than every element?
What condition is required for binary search?