Binary search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target. This function uses recursive call to itself. If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound.
(array []int, target int, lowIndex int, highIndex int)
| 4 | // This function uses recursive call to itself. |
| 5 | // If a target is found, the index of the target is returned. Else the function return -1 and ErrNotFound. |
| 6 | func Binary(array []int, target int, lowIndex int, highIndex int) (int, error) { |
| 7 | if highIndex < lowIndex || len(array) == 0 { |
| 8 | return -1, ErrNotFound |
| 9 | } |
| 10 | mid := int(lowIndex + (highIndex-lowIndex)/2) |
| 11 | if array[mid] > target { |
| 12 | return Binary(array, target, lowIndex, mid-1) |
| 13 | } else if array[mid] < target { |
| 14 | return Binary(array, target, mid+1, highIndex) |
| 15 | } else { |
| 16 | return mid, nil |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | // BinaryIterative search for target within a sorted array by repeatedly dividing the array in half and comparing the midpoint with the target. |
| 21 | // Unlike Binary, this function uses iterative method and not recursive. |
no outgoing calls