|
1 | | -"""Jump Search (https://www.geeksforgeeks.org/jump-search/). |
2 | | -
|
3 | | -A searching algorithm for sorted arrays. The basic idea |
4 | | -is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of |
5 | | -searching all elements. |
6 | | -
|
7 | | -For example, suppose we have an array arr[] of size n and block (to be jumped) size `m`. Then we search at the |
8 | | -indexes `arr[0]`, `arr[m]`, `arr[2m]…..arr[km]`, and so on. Once we find the interval (`arr[km] < x < arr[(k+1)m]`), |
9 | | -we perform a linear search operation from the index `km` to find the element `x`. |
10 | | -
|
11 | | -What is the optimal block size to be skipped? |
12 | | -In the worst case, we have to do `n/m` jumps and if the last checked value is greater than the element to be searched |
13 | | -for, we perform `m-1` comparisons more for linear search. Therefore the total number of comparisons in the worst case |
14 | | -will be `((n/m) + m-1)`. The value of the function `((n/m) + m-1)` will be minimum when `m = √n`. Therefore, the best |
15 | | -step size is `m = √n`. (Geeks For Geeks) |
16 | | -""" |
17 | | - |
18 | 1 | import math |
19 | 2 | from typing import Optional |
20 | 3 |
|
21 | 4 | from algorithm_theory.linear_search import linear_search |
22 | 5 |
|
23 | 6 |
|
24 | 7 | def jump_search(array: [int], target: int) -> Optional[int]: |
25 | | - """Jump ahead by blocks of size √n, then linear search within the block containing target.""" |
| 8 | + """Jump Search (https://www.geeksforgeeks.org/jump-search/). |
| 9 | +
|
| 10 | + A searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear |
| 11 | + search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements. |
| 12 | +
|
| 13 | + For example, suppose we have an array arr[] of size n and block (to be jumped) size `m`. Then we search |
| 14 | + at the indexes `arr[0]`, `arr[m]`, `arr[2m]…..arr[km]`, and so on. Once we find the interval |
| 15 | + (`arr[km] < x < arr[(k+1)m]`), we perform a linear search operation from the index `km` to find `x`. |
| 16 | +
|
| 17 | + What is the optimal block size to be skipped? |
| 18 | + In the worst case, we have to do `n/m` jumps and if the last checked value is greater than the element |
| 19 | + to be searched for, we perform `m-1` comparisons more for linear search. Therefore the total number of |
| 20 | + comparisons in the worst case will be `((n/m) + m-1)`. The value of the function `((n/m) + m-1)` will be |
| 21 | + minimum when `m = √n`. Therefore, the best step size is `m = √n`. (Geeks For Geeks) |
| 22 | + """ |
26 | 23 | length = len(array) |
27 | 24 | interval = int(math.sqrt(length)) |
28 | 25 | index = interval - 1 # 0 Based |
|
0 commit comments