Skip to content

Commit dbd8386

Browse files
authored
Merge pull request #77 from ghimiresdp/feat/jump-search
feat: add jump search example
2 parents 94ca100 + 1bf263b commit dbd8386

6 files changed

Lines changed: 193 additions & 11 deletions

File tree

.github/PULL_REQUEST_TEMPLATE.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
# SUMMARY
32
<!-- You can add all the commit messages as a list -->
43
<!-- using `gh pr create`, it will automatically append it at the top -->

README.md

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -120,16 +120,21 @@ cargo test --bin huffman
120120
1. [Linear Searching](crates/dsa/src/algorithms/searching/linear_search.rs)
121121

122122
```sh
123-
cargo run --bin linear_search
123+
cargo run --bin linear-search
124124
```
125125

126126
2. [Binary Searching](crates/dsa/src/algorithms/searching/binary_search.rs)
127127

128128
```sh
129-
cargo run --bin binary_search
129+
cargo run --bin binary-search
130+
```
131+
132+
3. [Jump Search](crates/dsa/src/algorithms/searching/jump_search.rs)
133+
134+
```sh
135+
cargo run --bin jump-search
130136
```
131137

132-
3. [Jump Search]
133138
4. [Interpolation Search]
134139

135140
#### [1.2.2. Sorting](crates/dsa/src/algorithms/sorting/)
@@ -190,7 +195,8 @@ cargo test --bin huffman
190195
8. [Topological Sort]
191196
9. [Depth First Search (DFS)](crates/dsa/src/algorithms/greedy/dfs.rs)
192197
193-
An example of a package manager to resolve and install dependencies using DFS approach.
198+
An example of a package manager to resolve and install dependencies using DFS
199+
algorithm.
194200
195201
```sh
196202
cargo run --bin dfs

crates/dsa/Cargo.toml

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,17 @@ path = "src/structures/trie.rs"
4747
# ================================[ Algorithms ]================================
4848
# Searching
4949
[[bin]]
50-
name = "linear_search"
50+
name = "linear-search"
5151
path = "src/algorithms/searching/linear_search.rs"
5252

5353
[[bin]]
54-
name = "binary_search"
54+
name = "binary-search"
5555
path = "src/algorithms/searching/binary_search.rs"
5656

57+
[[bin]]
58+
name = "jump-search"
59+
path = "src/algorithms/searching/jump_search.rs"
60+
5761
# Sorting
5862
[[bin]]
5963
name = "bubble_sort"

crates/dsa/src/algorithms/searching/binary_search.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
//! To run/test, please run the following commands in your terminal
44
//!
55
//! ```sh
6-
//! cargo run --bin binary_search
6+
//! cargo run --bin binary-search
77
//! ```
88
//!
99
//! ```sh
10-
//! cargo test --bin binary_search
10+
//! cargo test --bin binary-search
1111
//! ```
1212
//! Binary Searching algorithm uses divide and conquer method to recursively find
1313
//! out elements of a sorted array.
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
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+
}

crates/dsa/src/algorithms/searching/linear_search.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
//! To run/test, please run the following commands in your terminal
33
//!
44
//! ```sh
5-
//! cargo run --bin linear_search
5+
//! cargo run --bin linear-search
66
//! ```
77
//!
88
//! ```sh
9-
//! cargo test --bin linear_search
9+
//! cargo test --bin linear-search
1010
//! ```
1111
//!
1212
//! Linear searching algorithm is a sequential searching algorithm, where we

0 commit comments

Comments
 (0)