- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathJump_search.py
81 lines (34 loc) · 1.06 KB
/
Jump_search.py
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
# Python3 code to implement Jump Search
importmath
defjumpSearch( arr , x , n ):
# Finding block size to be jumped
step=math.sqrt(n)
# Finding the block where element is
# present (if it is present)
prev=0
whilearr[int(min(step, n)-1)] <x:
prev=step
step+=math.sqrt(n)
ifprev>=n:
return-1
# Doing a linear search for x in
# block beginning with prev.
whilearr[int(prev)] <x:
prev+=1
# If we reached next block or end
# of array, element is not present.
ifprev==min(step, n):
return-1
# If element is found
ifarr[int(prev)] ==x:
returnprev
return-1
# Driver code to test function
arr= [ 0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, 610 ]
x=55
n=len(arr)
# Find the index of 'x' using Jump Search
index=jumpSearch(arr, x, n)
# Print the index where 'x' is located
print("Number" , x, "is at index" ,"%.0f"%index)