-
Notifications
You must be signed in to change notification settings - Fork 1
/
BinarySearch.go
67 lines (63 loc) · 1.06 KB
/
BinarySearch.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
// BinarySearch
package main
import (
"fmt"
)
func bs(d []int, n int) int {
l := 0
h := len(d) - 1
for l <= h {
m := (l + h) / 2
if d[m] < n {
l = m + 1
} else if d[m] > n {
h = m - 1
} else {
return m
}
}
return -1
}
func bs_repeat(d []int, n int) (low, high int) {
/*
对上下限的条件判断,比如是否有等号,
可以举例判断。
求上限时,可以用8,8,9这样的数组判断;
求下限时,可以用8,9,9这样的数组判断.
*/
l := 0
h := len(d) - 1
for l < h {
m := (l + h + 1) / 2
if d[m] <= n {
l = m
} else {
h = m - 1
}
}
high = h
l = 0
h = high
for l < h {
m := (l + h) / 2
if d[m] >= n {
h = m
} else {
l = m + 1
}
}
low = l
return
}
func main() {
d := []int{4, 5, 6, 9, 10, 11, 15, 17, 19}
fmt.Println(d)
for i := 0; i < len(d); i++ {
fmt.Println(bs(d, d[i]))
}
dr := []int{4, 4, 5, 5, 9, 9, 9, 10, 11, 11}
fmt.Println(dr)
for i := 0; i < len(dr); i++ {
fmt.Println(bs_repeat(dr, dr[i]))
}
}