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

Function BinaryIterative

search/binary.go:23–38  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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.
23func 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.

Callers 2

TestBinaryIterativeFunction · 0.85
BenchmarkBinaryIterativeFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestBinaryIterativeFunction · 0.68
BenchmarkBinaryIterativeFunction · 0.68