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

Function Binary

search/binary.go:6–18  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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

Callers 2

TestBinaryFunction · 0.85
BenchmarkBinaryFunction · 0.85

Calls

no outgoing calls

Tested by 2

TestBinaryFunction · 0.68
BenchmarkBinaryFunction · 0.68