Python implementation of the jump search algorithm. Return the index if the `item` is found, otherwise return -1. 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,
(arr: Sequence[T], item: T)
| 18 | |
| 19 | |
| 20 | def jump_search[T: Comparable](arr: Sequence[T], item: T) -> int: |
| 21 | """ |
| 22 | Python implementation of the jump search algorithm. |
| 23 | Return the index if the `item` is found, otherwise return -1. |
| 24 | |
| 25 | Examples: |
| 26 | >>> jump_search([0, 1, 2, 3, 4, 5], 3) |
| 27 | 3 |
| 28 | >>> jump_search([-5, -2, -1], -1) |
| 29 | 2 |
| 30 | >>> jump_search([0, 5, 10, 20], 8) |
| 31 | -1 |
| 32 | >>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55) |
| 33 | 10 |
| 34 | >>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee") |
| 35 | 4 |
| 36 | """ |
| 37 | |
| 38 | arr_size = len(arr) |
| 39 | block_size = int(math.sqrt(arr_size)) |
| 40 | |
| 41 | prev = 0 |
| 42 | step = block_size |
| 43 | while arr[min(step, arr_size) - 1] < item: |
| 44 | prev = step |
| 45 | step += block_size |
| 46 | if prev >= arr_size: |
| 47 | return -1 |
| 48 | |
| 49 | while arr[prev] < item: |
| 50 | prev += 1 |
| 51 | if prev == min(step, arr_size): |
| 52 | return -1 |
| 53 | if arr[prev] == item: |
| 54 | return prev |
| 55 | return -1 |
| 56 | |
| 57 | |
| 58 | if __name__ == "__main__": |