4
4
until the element compared is bigger than the one searched.
5
5
It will then perform a linear search until it matches the wanted number.
6
6
If not found, it returns -1.
7
+
8
+ https://en.wikipedia.org/wiki/Jump_search
7
9
"""
8
10
9
11
import 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
+
10
20
21
+ T = TypeVar ("T" , bound = Comparable )
11
22
12
- def jump_search (arr : list , x : int ) -> int :
23
+
24
+ def jump_search (arr : Sequence [T ], item : T ) -> int :
13
25
"""
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
+
15
29
Examples:
16
30
>>> jump_search([0, 1, 2, 3, 4, 5], 3)
17
31
3
@@ -21,31 +35,36 @@ def jump_search(arr: list, x: int) -> int:
21
35
-1
22
36
>>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
23
37
10
38
+ >>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee")
39
+ 4
24
40
"""
25
41
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
+
28
45
prev = 0
29
- while arr [min (step , n ) - 1 ] < x :
46
+ step = block_size
47
+ while arr [min (step , arr_size ) - 1 ] < item :
30
48
prev = step
31
- step += int ( math . floor ( math . sqrt ( n )))
32
- if prev >= n :
49
+ step += block_size
50
+ if prev >= arr_size :
33
51
return - 1
34
52
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 ):
38
56
return - 1
39
- if arr [prev ] == x :
57
+ if arr [prev ] == item :
40
58
return prev
41
59
return - 1
42
60
43
61
44
62
if __name__ == "__main__" :
45
63
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 ("," )]
47
65
x = int (input ("Enter the number to be searched:\n " ))
48
- res = jump_search (arr , x )
66
+
67
+ res = jump_search (array , x )
49
68
if res == - 1 :
50
69
print ("Number not found!" )
51
70
else :
0 commit comments