-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.go
70 lines (64 loc) · 1.49 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
package search
func Binary(array []int, target int, lowIndex int, highIndex int) (int, error) {
if highIndex < lowIndex || len(array) == 0 {
return -1, ErrNotFound
}
mid := int(lowIndex + (highIndex-lowIndex)/2)
if array[mid] > target {
return Binary(array, target, lowIndex, mid-1)
} else if array[mid] < target {
return Binary(array, target, mid+1, highIndex)
} else {
return mid, nil
}
}
func BinaryIterative(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else if array[mid] < target {
startIndex = mid + 1
} else {
return mid, nil
}
}
return -1, ErrNotFound
}
func LowerBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] < target {
startIndex = mid + 1
} else {
endIndex = mid - 1
}
}
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}
func UpperBound(array []int, target int) (int, error) {
startIndex := 0
endIndex := len(array) - 1
var mid int
for startIndex <= endIndex {
mid = int(startIndex + (endIndex-startIndex)/2)
if array[mid] > target {
endIndex = mid - 1
} else {
startIndex = mid + 1
}
}
if startIndex >= len(array) {
return -1, ErrNotFound
}
return startIndex, nil
}