-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_search.go
47 lines (39 loc) · 926 Bytes
/
binary_search.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
package algorithms
// BinarySearch does a binary search. It assumes the slice is
// already sorted.
//
// Time O(log n) | Space O(1)
func BinarySearch(slice []int, search int) int {
min, max := 0, len(slice)-1
for min <= max {
middle := (min + max) / 2
if slice[middle] == search {
return middle
} else if slice[middle] < search {
min = middle + 1
} else {
max = middle - 1
}
}
return -1
}
// BinarySearchRecursive does the same as BinarySearch except recursively.
//
// Time O(log n) | Space O(1)
func BinarySearchRecursive(slice []int, search int) int {
var recurse func(min, max int) int
recurse = func(min, max int) int {
if min > max {
return -1
}
middle := (min + max) / 2
if slice[middle] == search {
return middle
} else if slice[middle] < search {
return recurse(middle+1, max)
} else {
return recurse(min, middle-1)
}
}
return recurse(0, len(slice)-1)
}