26 lines
657 B
Rust
26 lines
657 B
Rust
use std::collections::BTreeMap;
|
|
|
|
pub fn bucket_sort<T: Ord + Default + Copy, const SIZE: usize>(to_sort: &[T; SIZE]) -> [T; SIZE] {
|
|
// sort into buckets
|
|
let mut buckets = BTreeMap::new();
|
|
for item in to_sort {
|
|
buckets
|
|
.entry(item)
|
|
.and_modify(|count| *count += 1)
|
|
.or_insert(1);
|
|
}
|
|
|
|
// Create new array, copying items to new array
|
|
let mut result: [T; SIZE] = [T::default(); SIZE];
|
|
let mut pos = 0;
|
|
for (item, count) in buckets {
|
|
let mut i = 0;
|
|
while i < count {
|
|
result[pos] = *item;
|
|
i += 1;
|
|
pos += 1;
|
|
}
|
|
}
|
|
result
|
|
}
|