44until the element compared is bigger than the one searched.
55It will then perform a linear search until it matches the wanted number.
66If not found, it returns -1.
7+
8+ https://en.wikipedia.org/wiki/Jump_search
79"""
810
911import math
12+ from collections .abc import Sequence
13+ from typing import Any , Protocol , TypeVar
14+
15+
16+ class Comparable (Protocol ):
17+ def __lt__ (self , other : Any , / ) -> bool :
18+ ...
19+
1020
21+ T = TypeVar ("T" , bound = Comparable )
1122
12- def jump_search (arr : list , x : int ) -> int :
23+
24+ def jump_search (arr : Sequence [T ], item : T ) -> int :
1325 """
14- Pure Python implementation of the jump search algorithm.
26+ Python implementation of the jump search algorithm.
27+ Return the index if the `item` is found, otherwise return -1.
28+
1529 Examples:
1630 >>> jump_search([0, 1, 2, 3, 4, 5], 3)
1731 3
@@ -21,31 +35,36 @@ def jump_search(arr: list, x: int) -> int:
2135 -1
2236 >>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
2337 10
38+ >>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee")
39+ 4
2440 """
2541
26- n = len (arr )
27- step = int (math .floor (math .sqrt (n )))
42+ arr_size = len (arr )
43+ block_size = int (math .sqrt (arr_size ))
44+
2845 prev = 0
29- while arr [min (step , n ) - 1 ] < x :
46+ step = block_size
47+ while arr [min (step , arr_size ) - 1 ] < item :
3048 prev = step
31- step += int ( math . floor ( math . sqrt ( n )))
32- if prev >= n :
49+ step += block_size
50+ if prev >= arr_size :
3351 return - 1
3452
35- while arr [prev ] < x :
36- prev = prev + 1
37- if prev == min (step , n ):
53+ while arr [prev ] < item :
54+ prev += 1
55+ if prev == min (step , arr_size ):
3856 return - 1
39- if arr [prev ] == x :
57+ if arr [prev ] == item :
4058 return prev
4159 return - 1
4260
4361
4462if __name__ == "__main__" :
4563 user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
46- arr = [int (item ) for item in user_input .split ("," )]
64+ array = [int (item ) for item in user_input .split ("," )]
4765 x = int (input ("Enter the number to be searched:\n " ))
48- res = jump_search (arr , x )
66+
67+ res = jump_search (array , x )
4968 if res == - 1 :
5069 print ("Number not found!" )
5170 else :
0 commit comments