Skip to content

Commit f754c0d

Browse files
authored
Jump search (TheAlgorithms#2415)
* jump_search: doctest, docstring, type hint, inputs * jumpsearch.py: case number not found * trailing whitespace jump search
1 parent 2e790ce commit f754c0d

File tree

1 file changed

+30
-4
lines changed

1 file changed

+30
-4
lines changed

searches/jump_search.py

+30-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,28 @@
1+
"""
2+
Pure Python implementation of the jump search algorithm.
3+
This algorithm iterates through a sorted collection with a step of n^(1/2),
4+
until the element compared is bigger than the one searched.
5+
It will then perform a linear search until it matches the wanted number.
6+
If not found, it returns -1.
7+
"""
8+
19
import math
210

311

4-
def jump_search(arr, x):
12+
def jump_search(arr: list, x: int) -> int:
13+
"""
14+
Pure Python implementation of the jump search algorithm.
15+
Examples:
16+
>>> jump_search([0, 1, 2, 3, 4, 5], 3)
17+
3
18+
>>> jump_search([-5, -2, -1], -1)
19+
2
20+
>>> jump_search([0, 5, 10, 20], 8)
21+
-1
22+
>>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
23+
10
24+
"""
25+
526
n = len(arr)
627
step = int(math.floor(math.sqrt(n)))
728
prev = 0
@@ -21,6 +42,11 @@ def jump_search(arr, x):
2142

2243

2344
if __name__ == "__main__":
24-
arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
25-
x = 55
26-
print(f"Number {x} is at index {jump_search(arr, x)}")
45+
user_input = input("Enter numbers separated by a comma:\n").strip()
46+
arr = [int(item) for item in user_input.split(",")]
47+
x = int(input("Enter the number to be searched:\n"))
48+
res = jump_search(arr, x)
49+
if res == -1:
50+
print("Number not found!")
51+
else:
52+
print(f"Number {x} is at index {res}")

0 commit comments

Comments
 (0)