Add bubble sort
parent
e05db3b027
commit
593565c489
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "sorting"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
rand = "0.8.4"
|
@ -0,0 +1,35 @@
|
||||
pub mod bubble_sort {
|
||||
pub fn sort(vec: &mut Vec<usize>) {
|
||||
for outer in (0..vec.len()).rev() {
|
||||
for inner in 0..outer {
|
||||
if vec[inner] > vec[inner + 1] {
|
||||
super::swap(vec, inner, inner + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn swap(vec: &mut Vec<usize>, index_one: usize, index_two: usize) {
|
||||
let temp = vec[index_two];
|
||||
vec[index_two] = vec[index_one];
|
||||
vec[index_one] = temp;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod lib_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn can_swap_numbers() {
|
||||
// Arrange
|
||||
let mut vec = vec![1, 2];
|
||||
|
||||
// Act
|
||||
swap(&mut vec, 0, 1);
|
||||
|
||||
// Assert
|
||||
assert_eq!(vec[0], 2);
|
||||
assert_eq!(vec[1], 1);
|
||||
}
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
use rand::seq::SliceRandom;
|
||||
use sorting;
|
||||
use rand::thread_rng;
|
||||
|
||||
#[test]
|
||||
fn bubble_sort_ascending() {
|
||||
// Arrange
|
||||
let mut vec: Vec<usize> = (0..20).rev().collect();
|
||||
vec.shuffle(&mut thread_rng());
|
||||
|
||||
// Act
|
||||
sorting::bubble_sort::sort(&mut vec);
|
||||
|
||||
// Assert
|
||||
for i in 0..20 {
|
||||
assert_eq!(vec[i], i);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue