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