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

Function UpperBound

search/binary.go:64–82  ·  view source on GitHub ↗

UpperBound returns index to the first element in the range [lowIndex, len(array)-1] that is greater than target. return -1 and ErrNotFound if no such element is found.

(array []int, target int)

Source from the content-addressed store, hash-verified

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.
64func UpperBound(array []int, target int) (int, error) {
65 startIndex := 0
66 endIndex := len(array) - 1
67 var mid int
68 for startIndex <= endIndex {
69 mid = int(startIndex + (endIndex-startIndex)/2)
70 if array[mid] > target {
71 endIndex = mid - 1
72 } else {
73 startIndex = mid + 1
74 }
75 }
76
77 //when target greater or equal than every element in array, startIndex will out of bounds
78 if startIndex >= len(array) {
79 return -1, ErrNotFound
80 }
81 return startIndex, nil
82}

Callers 2

TestUpperBoundFunction · 0.85
BenchmarkUpperBoundFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestUpperBoundFunction · 0.68
BenchmarkUpperBoundFunction · 0.68