mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-01-30 14:13:44 +00:00
Jump search (#2415)
* jump_search: doctest, docstring, type hint, inputs * jumpsearch.py: case number not found * trailing whitespace jump search
This commit is contained in:
parent
2e790ce4ca
commit
f754c0d31f
|
@ -1,7 +1,28 @@
|
||||||
|
"""
|
||||||
|
Pure Python implementation of the jump search algorithm.
|
||||||
|
This algorithm iterates through a sorted collection with a step of n^(1/2),
|
||||||
|
until the element compared is bigger than the one searched.
|
||||||
|
It will then perform a linear search until it matches the wanted number.
|
||||||
|
If not found, it returns -1.
|
||||||
|
"""
|
||||||
|
|
||||||
import math
|
import math
|
||||||
|
|
||||||
|
|
||||||
def jump_search(arr, x):
|
def jump_search(arr: list, x: int) -> int:
|
||||||
|
"""
|
||||||
|
Pure Python implementation of the jump search algorithm.
|
||||||
|
Examples:
|
||||||
|
>>> jump_search([0, 1, 2, 3, 4, 5], 3)
|
||||||
|
3
|
||||||
|
>>> jump_search([-5, -2, -1], -1)
|
||||||
|
2
|
||||||
|
>>> jump_search([0, 5, 10, 20], 8)
|
||||||
|
-1
|
||||||
|
>>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
|
||||||
|
10
|
||||||
|
"""
|
||||||
|
|
||||||
n = len(arr)
|
n = len(arr)
|
||||||
step = int(math.floor(math.sqrt(n)))
|
step = int(math.floor(math.sqrt(n)))
|
||||||
prev = 0
|
prev = 0
|
||||||
|
@ -21,6 +42,11 @@ def jump_search(arr, x):
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
arr = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
||||||
x = 55
|
arr = [int(item) for item in user_input.split(",")]
|
||||||
print(f"Number {x} is at index {jump_search(arr, x)}")
|
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} is at index {res}")
|
||||||
|
|
Loading…
Reference in New Issue
Block a user