Add bucket_sort for arrays.
This commit is contained in:
parent
d9ed588c0e
commit
c27803f875
13
src/main.rs
13
src/main.rs
@ -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
22
src/sort.rs
Normal 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user