diff --git a/src/main.rs b/src/main.rs index 6096875..0606c18 100644 --- a/src/main.rs +++ b/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); } diff --git a/src/sort.rs b/src/sort.rs new file mode 100644 index 0000000..3c26552 --- /dev/null +++ b/src/sort.rs @@ -0,0 +1,22 @@ +use std::collections::BTreeMap; + +pub fn bucket_sort(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 +} \ No newline at end of file