-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.go
61 lines (57 loc) · 1.01 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
package search
func LinearSearchFloat64s(haystack []float64, needle float64) int {
n := len(haystack)
i := 0
// Unroll the loop for better ILP
for n >= 4 {
if haystack[i] >= needle {
if haystack[i] == needle {
return i
}
return len(haystack)
}
if haystack[i+1] >= needle {
if haystack[i+1] == needle {
return i + 1
}
return len(haystack)
}
if haystack[i+2] >= needle {
if haystack[i+2] == needle {
return i + 2
}
return len(haystack)
}
if haystack[i+3] >= needle {
if haystack[i+3] == needle {
return i + 3
}
return len(haystack)
}
i += 4
n -= 4
}
// Handle the remaining elements
for n > 0 {
if haystack[i] >= needle {
if haystack[i] == needle {
return i
}
return len(haystack)
}
i++
n--
}
return len(haystack)
}
func BasicLinearSearchFloat64s(haystack []float64, needle float64) int {
for i, v := range haystack {
if v >= needle {
if v == needle {
return i
}
return len(haystack)
}
}
return len(haystack)
}