Skip to content

Commit c1d252a

Browse files
Create jump_search.py
1 parent e0bde79 commit c1d252a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

sorting_searching/jump_search.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import math
2+
3+
def jumpSearch( arr , x , n ):
4+
5+
# Finding block size to be jumped
6+
step = math.sqrt(n)
7+
8+
# Finding the block where element is
9+
# present (if it is present)
10+
prev = 0
11+
while arr[int(min(step, n)-1)] < x:
12+
prev = step
13+
step += math.sqrt(n)
14+
if prev >= n:
15+
return -1
16+
17+
# Doing a linear search for x in
18+
# block beginning with prev.
19+
while arr[int(prev)] < x:
20+
prev += 1
21+
22+
# If we reached next block or end
23+
# of array, element is not present.
24+
if prev == min(step, n):
25+
return -1
26+
27+
# If element is found
28+
if arr[int(prev)] == x:
29+
return prev
30+
31+
return -1
32+
33+
# Driver code to test function
34+
arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21,
35+
34, 55, 89, 144, 233, 377, 610 ]
36+
x = 55
37+
n = len(arr)
38+
39+
# Find the index of 'x' using Jump Search
40+
index = jumpSearch(arr, x, n)
41+
42+
# Print the index where 'x' is located
43+
print("Number" , x, "is at index" ,"%.0f"%index)
44+
45+
# This code is contributed by "Sharad_Bhardwaj".

0 commit comments

Comments
 (0)