diff --git a/Chapter03/publish-crate/Cargo.toml b/Chapter03/publish-crate/Cargo.toml new file mode 100644 index 0000000..d3f539f --- /dev/null +++ b/Chapter03/publish-crate/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "bubble-sort" +description = "A quick and non-optimized, cloning version of the bubble sort algorithm. Created as a showcase for publishing crates in the Rust Cookbook 2018" +version = "0.2.0" +authors = ["Claus Matzinger "] +edition = "2018" +homepage = "https://blog.x5ff.xyz" +repository = "https://github.com/PacktPublishing/Rust-Cookbook" +license = "MIT" +categories = [ + "algorithms", +] +keywords = [ + "cookbook", + "packt", + "x5ff", + "bubble", + "sort", +] +readme = "README.md" +maintenance = { status = "experimental" } +#azure-devops = { project = "...", pipeline = "...", build="2" } + diff --git a/Chapter03/publish-crate/README.md b/Chapter03/publish-crate/README.md new file mode 100644 index 0000000..c0129d9 --- /dev/null +++ b/Chapter03/publish-crate/README.md @@ -0,0 +1,12 @@ +# Bubble Sort + +A non-optimal implemenation of the bubble sort algorithm. Best case runtime is `O(n)` - worst case `O(n^2)`. Read more on [wikipedia](https://en.wikipedia.org/wiki/Bubble_sort). + + +This crate was published to support a new version of the Rust Cookbook published by Packt Publishing and written by [Claus Matzinger](https://blog.x5ff.xyz). + +[Source code until the book is published](https://github.com/PacktPublishing/Hands-On-Data-Structures-and-Algorithms-with-Rust/blob/master/Chapter09/src/lib.rs) + +# License + +MIT \ No newline at end of file diff --git a/Chapter03/publish-crate/src/lib.rs b/Chapter03/publish-crate/src/lib.rs new file mode 100644 index 0000000..462a611 --- /dev/null +++ b/Chapter03/publish-crate/src/lib.rs @@ -0,0 +1,44 @@ +//! This is a non-optimized implementation of the [bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) algorithm for the book Rust Cookbook by Packt. This implementation also clones the input vector. +//! +//! # Examples +//!``` +//!# use bubble_sort::bubble_sort; +//! let v = vec![2, 2, 10, 1, 5, 4, 3]; +//! assert_eq!(bubble_sort(&v), vec![1, 2, 2, 3, 4, 5, 10]); +//!``` + +/// +/// See module level documentation. +/// +pub fn bubble_sort(collection: &[T]) -> Vec { + let mut result: Vec = collection.into(); + for _ in 0..result.len() { + let mut swaps = 0; + for i in 1..result.len() { + if result[i - 1] > result[i] { + result.swap(i - 1, i); + swaps += 1; + } + } + if swaps == 0 { + break; + } + } + result +} + +#[cfg(test)] +mod tests { + use super::bubble_sort; + #[test] + fn test_bubble_sort() { + assert_eq!(bubble_sort(&vec![9, 8, 7, 6]), vec![6, 7, 8, 9]); + assert_eq!(bubble_sort(&vec![9_f32, 8_f32, 7_f32, 6_f32]), vec![6_f32, 7_f32, 8_f32, 9_f32]); + + assert_eq!(bubble_sort(&vec!['c','f','a','x']), vec!['a', 'c', 'f', 'x']); + + assert_eq!(bubble_sort(&vec![6, 8, 7, 9]), vec![6, 7, 8, 9]); + assert_eq!(bubble_sort(&vec![2, 1, 1, 1, 1]), vec![1, 1, 1, 1, 2]); + } + +}