-
Notifications
You must be signed in to change notification settings - Fork 2
/
binary_search.go
79 lines (67 loc) · 1.72 KB
/
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
)
// Here's iterative.
func search(nums []int, target int) int {
start := 0
end := len(nums)
for {
if start == end - 1 {
if nums[start] == target {
return 0
}
return -1
}
middle := (end+start)/2
if nums[middle] == target {
return middle
}
if nums[middle] < target {
start = middle
continue
}
end = middle
}
}
// Here's recursive
const (
Smaller = iota - 1
Equal
Larger
)
func BinarySearch(sorted []int, start, end, value int) int {
if start == end-1 {
if sorted[start] == value {
return start
}
return -1
}
switch compareMiddle(sorted, start, end, value) {
case Equal:
return (start + end) / 2
case Larger:
return BinarySearch(sorted, (start+end)/2, end, value)
case Smaller:
return BinarySearch(sorted, start, (start+end)/2, value)
}
return -1
}
func compareMiddle(array []int, start, end, value int) int {
middle := (start + end) / 2
if value == array[middle] {
return Equal
} else if value > array[middle] {
return Larger
}
return Smaller
}
func main() {
var sorted = []int{-10, -8, -5, 0, 4, 16, 18, 23, 26, 30, 35, 41, 50, 55, 59, 67, 69}
fmt.Println("compareMiddle(20)", compareMiddle(sorted, 0, len(sorted), 20))
fmt.Println("BinarySearch(41)", BinarySearch(sorted, 0, len(sorted), 41))
fmt.Println("BinarySearch(3)", BinarySearch(sorted, 0, len(sorted), 3))
fmt.Println("BinarySearch(-10)", BinarySearch(sorted, 0, len(sorted), -10))
fmt.Println("BinarySearch(69)", BinarySearch(sorted, 0, len(sorted), 69))
fmt.Println("BinarySearch(67)", BinarySearch(sorted, 0, len(sorted), 67))
}