Skip to content

Commit cf1cabe

Browse files
authored
Add pigeonhole sort (TheAlgorithms#342)
1 parent 1b9e979 commit cf1cabe

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ These are for demonstration purposes only.
2020
- [x] [Merge](./src/sorting/merge_sort.rs)
2121
- [x] [Odd-even](./src/sorting/odd_even_sort.rs)
2222
- [x] [Pancake](./src/sorting/pancake_sort.rs)
23+
- [x] [Pigeonhole](./src/sorting/pigeonhole_sort.rs)
2324
- [x] [Quick](./src/sorting/quick_sort.rs)
2425
- [x] [Radix](./src/sorting/radix_sort.rs)
2526
- [x] [Selection](./src/sorting/selection_sort.rs)

src/sorting/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ mod insertion_sort;
1212
mod merge_sort;
1313
mod odd_even_sort;
1414
mod pancake_sort;
15+
mod pigeonhole_sort;
1516
mod quick_sort;
1617
mod radix_sort;
1718
mod selection_sort;
@@ -34,6 +35,7 @@ pub use self::insertion_sort::insertion_sort;
3435
pub use self::merge_sort::merge_sort;
3536
pub use self::odd_even_sort::odd_even_sort;
3637
pub use self::pancake_sort::pancake_sort;
38+
pub use self::pigeonhole_sort::pigeonhole_sort;
3739
pub use self::quick_sort::{partition, quick_sort};
3840
pub use self::radix_sort::radix_sort;
3941
pub use self::selection_sort::selection_sort;

src/sorting/pigeonhole_sort.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// From Wikipedia: Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the length of the range of possible key values (N) are approximately the same. It requires O(n + N) time.
2+
3+
pub fn pigeonhole_sort(array: &mut [i32]) {
4+
if let (Some(min), Some(max)) = (array.iter().min(), array.iter().max()) {
5+
let holes_range: usize = (max - min + 1) as usize;
6+
let mut holes = vec![0; holes_range];
7+
let mut holes_repeat = vec![0; holes_range];
8+
for i in array.iter() {
9+
let index = *i - min;
10+
holes[index as usize] = *i;
11+
holes_repeat[index as usize] += 1;
12+
}
13+
let mut index = 0;
14+
for i in 0..holes_range {
15+
while holes_repeat[i] > 0 {
16+
array[index] = holes[i];
17+
index += 1;
18+
holes_repeat[i] -= 1;
19+
}
20+
}
21+
}
22+
}
23+
24+
#[cfg(test)]
25+
mod tests {
26+
use super::super::is_sorted;
27+
use super::*;
28+
29+
#[test]
30+
fn test1() {
31+
let mut arr1 = [3, 3, 3, 1, 2, 6, 5, 5, 5, 4, 1, 6, 3];
32+
pigeonhole_sort(&mut arr1);
33+
assert!(is_sorted(&arr1));
34+
let mut arr2 = [6, 5, 4, 3, 2, 1];
35+
pigeonhole_sort(&mut arr2);
36+
assert!(is_sorted(&arr2));
37+
}
38+
}

0 commit comments

Comments
 (0)