Add bucket_sort for arrays.

This commit is contained in:
Jesse Brault 2024-11-22 21:08:16 -06:00
parent d9ed588c0e
commit c27803f875
2 changed files with 35 additions and 0 deletions

View File

@ -1,8 +1,10 @@
mod bst;
mod stack;
mod sort;
use bst::BinarySearchTree;
use stack::Stack;
use sort::bucket_sort;
struct Greeter {
greeting: &'static str,
@ -62,4 +64,15 @@ fn main() {
unsafe {
print_num(find_result);
}
// linear bucket sort
let items = [3, 2, 1, 1, 2, 3, 4];
println!("before sort: {:?}", items);
let sorted = bucket_sort(&items);
println!("sorted: {:?}", sorted);
let some_chars = ['a', 'b', 'c', 'c', 'a', 'b', 'd'];
let sorted_chars = bucket_sort(&some_chars);
println!("sorted chars: {:?}", sorted_chars);
}

22
src/sort.rs Normal file
View File

@ -0,0 +1,22 @@
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
}