-
-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathjumpserach.go
More file actions
40 lines (32 loc) · 786 Bytes
/
jumpserach.go
File metadata and controls
40 lines (32 loc) · 786 Bytes
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
package JumpSearch
import "math"
func jumpSearch(arr []int, query int) int {
size := len(arr)
step := int(math.Sqrt(float64(size)))
prev := 0
// We can't find anything in empty array
if size == 0 {
return -1
}
// Finding the block where element is present (if it is present)
for arr[int(math.Min(float64(step), float64(size)))-1] < query {
prev = step
step += int(math.Sqrt(float64(size)))
if prev >= size {
return -1
}
}
// Doing a linear search for x in block beginning with prev
for arr[prev] < query {
prev++
// If we reached next block or end of array, element is not present.
if prev == int(math.Min(float64(step), float64(size))) {
return -1
}
}
// Check if the element is found
if arr[prev] == query {
return prev
}
return -1
}