-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.go
63 lines (53 loc) · 971 Bytes
/
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
package main
import (
"math"
)
func linearSearch(arr []int, value int) int {
for i, v := range arr {
if v == value {
return i
}
}
return -1
}
func BinarySearch(arr []int, target int) int {
low, high := 0, len(arr)-1
for low <= high {
mid := low + (high-low)/2
if arr[mid] == target {
return mid
} else if target > arr[mid] {
low = mid + 1
} else {
high = mid - 1
}
}
return -1
}
func SearchInt(arr []int, val int, ordered bool) int {
if ordered {
if len(arr) > 10000 {
return TestBinarySearch(arr, val)
} else {
return TestLinearSearch(arr, val)
}
}
return TestLinearSearch(arr, val)
}
func BinaryCrystalBall(breaks []bool) int {
jumpAmount := int(math.Floor(math.Sqrt(float64(len(breaks)))))
i := jumpAmount
for ; i < len(breaks); i += jumpAmount {
if breaks[i] {
break
}
}
i -= jumpAmount
for j := 0; j < jumpAmount && i < len(breaks); j++ {
if breaks[i] {
return i
}
i++
}
return -1
}