MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / LowerBound

Function LowerBound

search/binary.go:42–60  ·  view source on GitHub ↗

LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target. return -1 and ErrNotFound if no such element is found.

(array []int, target int)

Source from the content-addressed store, hash-verified

40// LowerBound returns index to the first element in the range [0, len(array)-1] that is not less than (i.e. greater or equal to) target.
41// return -1 and ErrNotFound if no such element is found.
42func LowerBound(array []int, target int) (int, error) {
43 startIndex := 0
44 endIndex := len(array) - 1
45 var mid int
46 for startIndex <= endIndex {
47 mid = int(startIndex + (endIndex-startIndex)/2)
48 if array[mid] < target {
49 startIndex = mid + 1
50 } else {
51 endIndex = mid - 1
52 }
53 }
54
55 //when target greater than every element in array, startIndex will out of bounds
56 if startIndex >= len(array) {
57 return -1, ErrNotFound
58 }
59 return startIndex, nil
60}
61
62// UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target.
63// return -1 and ErrNotFound if no such element is found.

Callers 2

TestLowerBoundFunction · 0.85
BenchmarkLowerBoundFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestLowerBoundFunction · 0.68
BenchmarkLowerBoundFunction · 0.68