|
| 1 | +//! # Jump Search |
| 2 | +//! |
| 3 | +//! To run/test, please run the following commands in your terminal |
| 4 | +//! |
| 5 | +//! ```sh |
| 6 | +//! cargo run --bin jump-search |
| 7 | +//! ``` |
| 8 | +//! |
| 9 | +//! ```sh |
| 10 | +//! cargo test --bin jump-search |
| 11 | +//! ``` |
| 12 | +//! Jump Searching algorithm uses divide and conquer method to find out elements |
| 13 | +//! of a sorted array. This algorithm works by jumping ahead by fixed steps or |
| 14 | +//! blocks to find the desired element, and then performing a linear search |
| 15 | +//! within the identified block. |
| 16 | +//! |
| 17 | +//! For an ordered array of size n, the optimal jump size is √n, which minimizes |
| 18 | +//! the number of comparisons needed to find the desired element. Hence, the |
| 19 | +//! time complexity of jump search is O(√n). |
| 20 | +//! |
| 21 | +//! Jump search is more efficient than linear search for larger arrays, but less |
| 22 | +//! efficient than binary search. It is particularly useful when the cost of |
| 23 | +//! jumping ahead is less than the cost of performing multiple comparisons, such |
| 24 | +//! as in scenarios involving slow memory access or disk reads. |
| 25 | +//! |
| 26 | +//! **Note:** Jump search works only on the sorted array. If an array is |
| 27 | +//! not sorted, we must sort it before we can implement this algorithm. |
| 28 | +//! |
| 29 | +//! Example: |
| 30 | +//! |
| 31 | +//! we have an array `[1, 3, 4, 6, 7, 8, 9, 11, 15]` and we want to find out an |
| 32 | +//! index of `7`. |
| 33 | +//! |
| 34 | +//! ### steps |
| 35 | +//! 1. jump ahead by √n (i.e., 3) to index 2, compare the item (4 < 7) |
| 36 | +//! 2. jump ahead by √n to index 5, compare the item (8 > 7) (stop here as we have |
| 37 | +//! crossed the desired item) |
| 38 | +//! 3. perform linear search from index 3 to 5 |
| 39 | +//! 4. compare item at index 3 (6 < 7) |
| 40 | +//! 5. compare item at index 4 (7 == 7); return index of that number |
| 41 | +//! |
| 42 | +use std::cmp::Ordering::{Equal, Greater, Less}; |
| 43 | +use utils::parse_input; // common library for this repository |
| 44 | + |
| 45 | +fn jump_search(array: &mut [i32], item: i32) -> Option<usize> { |
| 46 | + if array.is_empty() { |
| 47 | + return None; |
| 48 | + } |
| 49 | + |
| 50 | + // step = √n, ensure at least 1 |
| 51 | + let step = ((array.len() as f64).sqrt().ceil() as usize).max(1); |
| 52 | + let mut left = 0; |
| 53 | + let mut right = step.min(array.len().saturating_sub(1)); |
| 54 | + |
| 55 | + // item out of bounds |
| 56 | + if item < array[0] || item > array[array.len() - 1] { |
| 57 | + return None; |
| 58 | + } |
| 59 | + |
| 60 | + // quick check for first element |
| 61 | + if array[left] == item { |
| 62 | + return Some(left); |
| 63 | + } |
| 64 | + |
| 65 | + while left < array.len() { |
| 66 | + println!("⛔ index [{:2}] to [{:2}]", left, right); |
| 67 | + match array[right].cmp(&item) { |
| 68 | + Greater => { |
| 69 | + println!("🔍 Searching between indexes [{:2}] to [{:2}]", left, right); |
| 70 | + for idx in left..=right { |
| 71 | + if array[idx] == item { |
| 72 | + return Some(idx); |
| 73 | + } |
| 74 | + if array[idx] > item { |
| 75 | + return None; |
| 76 | + } |
| 77 | + } |
| 78 | + return None; |
| 79 | + } |
| 80 | + Equal => return Some(right), |
| 81 | + Less => { |
| 82 | + left = right; |
| 83 | + right = right.saturating_add(step); |
| 84 | + if right > array.len() - 1 { |
| 85 | + right = array.len() - 1; |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + None |
| 92 | +} |
| 93 | + |
| 94 | +fn main() { |
| 95 | + let mut sorted_array = [1, 4, 7, 8, 9, 10, 11, 12, 15, 20]; |
| 96 | + println!("Sorted Array: {:?}", &sorted_array); |
| 97 | + // ! input() is a common library function, not included in std |
| 98 | + if let Ok(search_item) = parse_input("Enter a number to search: ") { |
| 99 | + return match jump_search(sorted_array.as_mut(), search_item) { |
| 100 | + Some(idx) => println!("The item {} is at index: {}", search_item, idx), |
| 101 | + None => println!("The item {} does not exist in the array", search_item), |
| 102 | + }; |
| 103 | + } |
| 104 | + println!("Invalid number Entered") |
| 105 | +} |
| 106 | +#[cfg(test)] |
| 107 | +mod tests { |
| 108 | + use crate::jump_search; |
| 109 | + |
| 110 | + #[test] |
| 111 | + fn search_ok() { |
| 112 | + assert_eq!(jump_search([1, 4, 2, 5, 7].as_mut(), 5), Some(3)) |
| 113 | + } |
| 114 | + |
| 115 | + #[test] |
| 116 | + fn search_err() { |
| 117 | + assert_eq!(jump_search([1, 4, 2, 5, 7].as_mut(), 8), None) |
| 118 | + } |
| 119 | + |
| 120 | + // Simple linear congruential generator for deterministic pseudo-random numbers |
| 121 | + fn lcg(seed: &mut u64) -> u64 { |
| 122 | + *seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); |
| 123 | + *seed |
| 124 | + } |
| 125 | + |
| 126 | + fn gen_sorted_array(n: usize, mut seed: u64) -> Vec<i32> { |
| 127 | + let mut v = Vec::with_capacity(n); |
| 128 | + for _ in 0..n { |
| 129 | + let r = lcg(&mut seed); |
| 130 | + // use upper bits to get a 32-bit-ish value |
| 131 | + v.push((r >> 16) as i32); |
| 132 | + } |
| 133 | + v.sort_unstable(); |
| 134 | + v |
| 135 | + } |
| 136 | + |
| 137 | + #[test] |
| 138 | + fn random_present() { |
| 139 | + let sizes = [1, 2, 5, 10, 50, 101, 500]; |
| 140 | + for (si, &n) in sizes.iter().enumerate() { |
| 141 | + let seed = 0xDEADBEEF_u64.wrapping_add(si as u64); |
| 142 | + let arr = gen_sorted_array(n, seed); |
| 143 | + if arr.is_empty() { |
| 144 | + continue; |
| 145 | + } |
| 146 | + for pick in 0..arr.len() { |
| 147 | + let key = arr[pick]; |
| 148 | + let mut v = arr.clone(); |
| 149 | + let res = jump_search(v.as_mut_slice(), key); |
| 150 | + assert!(res.is_some(), "expected to find {} in {:?}", key, v); |
| 151 | + let idx = res.unwrap(); |
| 152 | + assert_eq!(v[idx], key); |
| 153 | + } |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + #[test] |
| 158 | + fn random_absent() { |
| 159 | + let sizes = [1, 2, 5, 10, 50, 101, 500]; |
| 160 | + for (si, &n) in sizes.iter().enumerate() { |
| 161 | + let seed = 0xBEEFDEAD_u64.wrapping_add(si as u64); |
| 162 | + let arr = gen_sorted_array(n, seed); |
| 163 | + if arr.is_empty() { |
| 164 | + continue; |
| 165 | + } |
| 166 | + let mut v = arr.clone(); |
| 167 | + // pick a value greater than the max in array |
| 168 | + let last = *v.last().unwrap(); |
| 169 | + let key = last.wrapping_add(1); |
| 170 | + assert_eq!(jump_search(v.as_mut_slice(), key), None); |
| 171 | + } |
| 172 | + } |
| 173 | +} |
0 commit comments