~telemachus/algorithms

ref: 597d3c5170b0fd3982a2aa1d12e39179f2293bbf algorithms/binarysearch.go -rw-r--r-- 306 bytes
597d3c51Peter Aronoff Improve the README 1 year, 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package algorithms

func BinarySearch(xs []int, wanted int) int {
	min := 0
	max := len(xs) - 1
	var guess int

	for min <= max {
		guess = (min + max) / 2
		switch {
		case xs[guess] < wanted:
			min = guess + 1
		case xs[guess] > wanted:
			max = guess - 1
		default:
			return guess
		}
	}
	return -1
}