Binary Search Variant With Lower Bound (Go)
Find the leftmost position where a sorted slice can accept a target using a Go binary search lower bound variant.
Code
package main
import "fmt"
func lowerBound(arr []int, target int) int {
lo, hi := 0, len(arr)
for lo < hi {
mid := (lo + hi) / 2
if arr[mid] < target {
lo = mid + 1
} else {
hi = mid
}
}
return lo
}
func main() {
arr := []int{1, 2, 2, 3, 4, 6}
fmt.Println(lowerBound(arr, 2))
fmt.Println(lowerBound(arr, 5))
}Report a problem with this exampleOpens a pre-filled issue on GitHub.