-
Notifications
You must be signed in to change notification settings - Fork 2
/
search.go
85 lines (66 loc) · 1.58 KB
/
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
80
81
82
83
84
85
package binsrch
import "errors"
type Point struct {
X int
Y int
}
func Search(points []Point, abscissa int) (int, int, error) {
if len(points) == 0 {
return 0, 0, errors.New("points empty")
}
lower, err := findLower(0, len(points), points, abscissa)
if err != nil {
return 0, 0, err
}
upper := findUpper(0, len(points), points, abscissa)
return lower, upper, nil
}
func findLower(lower int, upper int, points []Point, abscissa int) (int, error) {
size := upper - lower
if size == 1 {
if points[lower].X == abscissa {
return lower, nil
}
return 0, errors.New("not found")
}
middle := size / 2
rightLower := lower + middle
leftUpper := upper - middle
point := points[rightLower]
x := point.X
if x == abscissa {
preceding := points[rightLower-1]
if preceding.X != abscissa {
return rightLower, nil
}
}
if x < abscissa {
return findLower(rightLower, upper, points, abscissa)
}
return findLower(lower, leftUpper, points, abscissa)
}
func findUpper(lower int, upper int, points []Point, abscissa int) int {
size := upper - lower
if size == 1 {
return upper
}
middle := size / 2
rightLower := lower + middle
leftUpper := upper - middle
point := points[rightLower]
x := point.X
if x == abscissa {
if rightLower+1 < len(points) {
succeeding := points[rightLower+1]
if succeeding.X == abscissa {
return findUpper(rightLower, upper, points, abscissa)
}
return rightLower + 1
}
return rightLower + 1
}
if x < abscissa {
return findUpper(rightLower, upper, points, abscissa)
}
return findUpper(lower, leftUpper, points, abscissa)
}