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)
| 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. |
| 64 | func 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 | } |
no outgoing calls