-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjump_search.py
More file actions
49 lines (34 loc) · 936 Bytes
/
jump_search.py
File metadata and controls
49 lines (34 loc) · 936 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
41
42
43
44
45
46
47
48
49
"""
This program implements the use of jump search on an array.
"""
import math
def jump_search(array, match, elements):
step = math.sqrt(elements)
prev = 0
while array[int(min(step, elements) - 1)] < match:
prev = step
step += step
if prev >= elements:
return False
while array[int(prev)] < match:
prev += 1
if prev == min(step, elements):
return False
if array[int(prev)] == match:
return True
arr = []
n = int(input('Enter the number of elements in the array: '))
for i in range(n):
arr.append(int(input('Enter array element: ')))
x = int(input('Enter the element you want to search: '))
arr.sort()
pos = 0
for i in range(len(arr)):
if arr[i] == x:
pos = i
result = jump_search(arr, x, n)
if result:
print('The element is present at position: ', pos)
else:
print('The element is not present.')
input()