BinaryIterative search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target. Unlike Binary, this function uses iterative method and not recursive. If a target is found, the index of the target is returned. Else the function return -1 an
(array []int, target int)
| 21 | // Unlike Binary, this function uses iterative method and not recursive. |
| 22 | // If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound. |
| 23 | func BinaryIterative(array []int, target int) (int, error) { |
| 24 | startIndex := 0 |
| 25 | endIndex := len(array) - 1 |
| 26 | var mid int |
| 27 | for startIndex <= endIndex { |
| 28 | mid = int(startIndex + (endIndex-startIndex)/2) |
| 29 | if array[mid] > target { |
| 30 | endIndex = mid - 1 |
| 31 | } else if array[mid] < target { |
| 32 | startIndex = mid + 1 |
| 33 | } else { |
| 34 | return mid, nil |
| 35 | } |
| 36 | } |
| 37 | return -1, ErrNotFound |
| 38 | } |
| 39 | |
| 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. |
no outgoing calls