generated from eng618/template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary.go
49 lines (41 loc) · 1.04 KB
/
binary.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package search
// BinaryLoop is an algorithm that uses the binary search method to search a given slice.
// We are expecting a sorted slice, otherwise the result will not be accurate.
//
// https://goplay.space/#TQBxLBIrt-w
//
// https://play.golang.org/p/TQBxLBIrt-w
func BinaryLoop(xi []int, target int) (index int, ok bool) {
min, max := 0, len(xi)-1
for min <= max {
guess := (min + max) / 2
switch {
case xi[guess] == target:
return guess, true
case xi[guess] < target:
min = guess + 1
default:
max = guess - 1
}
}
return -1, false
}
// BinaryRecursion uses the recursion method to call itself, until it
// determines if the target is present in the slice (which must be sorted).
func BinaryRecursion(xi []int, target int) bool {
if len(xi) == 0 {
return false
}
if len(xi) == 1 {
return xi[0] == target
}
middle := len(xi) / 2
switch {
case xi[middle] == target:
return true
case xi[middle] < target:
return BinaryRecursion(xi[middle+1:], target)
default:
return BinaryRecursion(xi[:middle], target)
}
}