Skip to content

Commit b649e00

Browse files
authored
Jump Search
It works only on sorted arrays.Binary Search is better than Jump Search, but Jump search has an advantage that we traverse back only once (Binary Search may require up to O(Log n) jumps, consider a situation where the element to be search is the smallest element or smaller than the smallest). So in a systems where jumping back is costly, we use Jump Search.
1 parent c20b2b7 commit b649e00

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Arrays-searching/jumpSearch.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#Jump Search by Master-Fury
2+
#Time Complexity : O(√n)
3+
4+
import math
5+
#Function for Jump Search
6+
def jumpSearch(arr,x,n): #arr is an array with n as length of array and x is searching element
7+
step=math.sqrt(n) #calculates jumping step
8+
prev = 0
9+
while arr[int(min(step,n)-1)]<x:
10+
prev=step
11+
step+=math.sqrt(n)
12+
if prev >= n:
13+
return -1
14+
while arr[int(prev)] < x: #if searching element is greater than previous.
15+
prev +=1
16+
17+
if prev==min(step,n):
18+
return -1
19+
if arr[int(prev)]==x:
20+
return prev
21+
return -1
22+
23+
24+
25+
26+
#Driver Code
27+
arr=[0,2,2,4,6,41,56,312,567,864] #your array
28+
n=len(arr)
29+
x=2 #your searching element
30+
result = int(jumpSearch(arr,x,n)) #calling funtion jumpSearch for result
31+
if result == -1:
32+
print ("Element not found in the array")
33+
else:
34+
print("Element found at position",result)

0 commit comments

Comments
 (0)