add publish-crate

pull/8/head
Claus Matzinger 2019-10-08 14:50:56 +02:00
rodzic 68183b9d24
commit 16a31fb177
3 zmienionych plików z 79 dodań i 0 usunięć

Wyświetl plik

@ -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 <claus.matzinger+kb@gmail.com>"]
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" }

Wyświetl plik

@ -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

Wyświetl plik

@ -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<T: PartialOrd + Clone>(collection: &[T]) -> Vec<T> {
let mut result: Vec<T> = 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]);
}
}