2020-09-12 05:50:12 +00:00
|
|
|
"""
|
|
|
|
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.
|
2023-08-08 21:47:09 +00:00
|
|
|
|
|
|
|
https://en.wikipedia.org/wiki/Jump_search
|
2020-09-12 05:50:12 +00:00
|
|
|
"""
|
|
|
|
|
2017-10-12 09:10:15 +00:00
|
|
|
import math
|
2023-08-08 21:47:09 +00:00
|
|
|
from collections.abc import Sequence
|
|
|
|
from typing import Any, Protocol, TypeVar
|
|
|
|
|
|
|
|
|
|
|
|
class Comparable(Protocol):
|
|
|
|
def __lt__(self, other: Any, /) -> bool:
|
|
|
|
...
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2023-08-08 21:47:09 +00:00
|
|
|
T = TypeVar("T", bound=Comparable)
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2023-08-08 21:47:09 +00:00
|
|
|
|
|
|
|
def jump_search(arr: Sequence[T], item: T) -> int:
|
2020-09-12 05:50:12 +00:00
|
|
|
"""
|
2023-08-08 21:47:09 +00:00
|
|
|
Python implementation of the jump search algorithm.
|
|
|
|
Return the index if the `item` is found, otherwise return -1.
|
|
|
|
|
2020-09-12 05:50:12 +00:00
|
|
|
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
|
2023-08-08 21:47:09 +00:00
|
|
|
>>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee")
|
|
|
|
4
|
2020-09-12 05:50:12 +00:00
|
|
|
"""
|
|
|
|
|
2023-08-08 21:47:09 +00:00
|
|
|
arr_size = len(arr)
|
|
|
|
block_size = int(math.sqrt(arr_size))
|
|
|
|
|
2017-10-12 09:10:15 +00:00
|
|
|
prev = 0
|
2023-08-08 21:47:09 +00:00
|
|
|
step = block_size
|
|
|
|
while arr[min(step, arr_size) - 1] < item:
|
2017-10-12 09:10:15 +00:00
|
|
|
prev = step
|
2023-08-08 21:47:09 +00:00
|
|
|
step += block_size
|
|
|
|
if prev >= arr_size:
|
2017-10-12 09:10:15 +00:00
|
|
|
return -1
|
|
|
|
|
2023-08-08 21:47:09 +00:00
|
|
|
while arr[prev] < item:
|
|
|
|
prev += 1
|
|
|
|
if prev == min(step, arr_size):
|
2017-10-12 09:10:15 +00:00
|
|
|
return -1
|
2023-08-08 21:47:09 +00:00
|
|
|
if arr[prev] == item:
|
2017-10-12 09:10:15 +00:00
|
|
|
return prev
|
|
|
|
return -1
|
|
|
|
|
|
|
|
|
2020-01-18 12:24:33 +00:00
|
|
|
if __name__ == "__main__":
|
2020-09-12 05:50:12 +00:00
|
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
2023-08-08 21:47:09 +00:00
|
|
|
array = [int(item) for item in user_input.split(",")]
|
2020-09-12 05:50:12 +00:00
|
|
|
x = int(input("Enter the number to be searched:\n"))
|
2023-08-08 21:47:09 +00:00
|
|
|
|
|
|
|
res = jump_search(array, x)
|
2020-09-12 05:50:12 +00:00
|
|
|
if res == -1:
|
|
|
|
print("Number not found!")
|
|
|
|
else:
|
|
|
|
print(f"Number {x} is at index {res}")
|