forked from souravjain540/Basic-Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjump_search.py
More file actions
37 lines (27 loc) · 767 Bytes
/
jump_search.py
File metadata and controls
37 lines (27 loc) · 767 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
import math
def jump_search(arr ,x):
n=len(arr)
jump=int(math.floor(math.sqrt(n)))
prev=0
while arr[min(jump,n) -1] < x:
prev=jump
jump += int(math.floor(math.sqrt(n)))
if prev >= n:
return -1
while arr[prev] < x:
prev=prev + 1
if prev == min(jump,n):
return -1
if arr[prev] == x:
print(prev)
return prev
return -1
if __name__=="__main__":
user_input=input("Enter numbers separated by a comma:\n").strip()
arr=[int(item) for item in user_input.split(",")]
x=int(input("Enter the number to be searched:\n"))
res=jump_search(arr,x)
if res == -1:
print("Number not found.")
else:
print(f"Number {x} found at {res}")