|
| 1 | +function found_at = jump_search(input_array, search_key) |
| 2 | + % Contributed by - Harshit Pant, [email protected] |
| 3 | + % Reference - https://en.wikipedia.org/wiki/Jump_search |
| 4 | + |
| 5 | + % input_array - Holds the array in which the 'search_key' is to be searched. |
| 6 | + % It should be sorted in ascending order. |
| 7 | + % It can contain -ve numbers as well as non-integers. |
| 8 | + % search_key - The value to be searched in the 'input_array'. |
| 9 | + % found_at - The index at which 'search_key' is found in 'input_array'. |
| 10 | + % -1 is returned if 'search_key' is not found in 'input_array'. |
| 11 | + |
| 12 | + array_length = length(input_array); |
| 13 | + found_at = -1; |
| 14 | + |
| 15 | + % Finding the optimum block_size to be jumped. |
| 16 | + block_size = sqrt(array_length); |
| 17 | + block_size = round(block_size); |
| 18 | + |
| 19 | + % low and high denote the lower |
| 20 | + % and upper bound of a certain block. |
| 21 | + low = 1; |
| 22 | + high = 1 + block_size; |
| 23 | + |
| 24 | + % Finding the block where the 'search_key' is present |
| 25 | + % if low >= array_length, the 'search_key' is not found |
| 26 | + % in the 'input_array', thus, -1 is returned. |
| 27 | + while input_array(min(high, array_length)) < search_key |
| 28 | + low = high; |
| 29 | + high = high + block_size; |
| 30 | + if low >= array_length |
| 31 | + return; |
| 32 | + endif; |
| 33 | + endwhile; |
| 34 | + |
| 35 | + % Now that the required block is found, |
| 36 | + % running a linear search within the block |
| 37 | + % to find the 'search_key' |
| 38 | + while input_array(low) < search_key |
| 39 | + low = low + 1; |
| 40 | + if low > min(high, array_length) |
| 41 | + return; |
| 42 | + endif; |
| 43 | + endwhile; |
| 44 | + |
| 45 | + % Checks if the 'search_key' was found within |
| 46 | + % the block. If found, the index is returned. |
| 47 | + % If not -1 is returned. |
| 48 | + if input_array(low) == search_key |
| 49 | + found_at = low; |
| 50 | + endif; |
| 51 | + |
| 52 | +endfunction; |
| 53 | + |
| 54 | +% TEST: |
| 55 | +% jump_search([-11.1, -3.3, -1.3, 0.1, 1.5, 3.5, 3.9,... |
| 56 | +% 5.5, 7.5, 9.6, 13.7, 21.3, 35.9], 7.5) == 9 |
0 commit comments