Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement stalinsort #6

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@
//! let sorted: Vec<_> = unsorted.sleepsort().collect();
//! ```
//!
//! ## Stalinsort
//!
//! Stalinsort is a very fast sorting algorithm that removes out of order items.
//! Has time and space complexity of O(n),
//! but you may not recognize the list afterwards.
//!
//! ```
//! # use sorting::*;
//! let mut unsorted = vec![5,7,8,1,0];
//! unsorted.stalinsort();
//! ```
//!
//! ## Miraclesort
//!
//! A sorting algorithm that waits for a miracle that automatically makes your vector
Expand All @@ -69,9 +81,11 @@ mod bogosort;
mod panicsort;
mod sleepsort;
mod miraclesort;
mod stalinsort;

pub use crate::slowsort::*;
pub use crate::bogosort::*;
pub use crate::panicsort::*;
pub use crate::sleepsort::*;
pub use crate::miraclesort::*;
pub use crate::stalinsort::*;
22 changes: 22 additions & 0 deletions src/stalinsort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/// This trait provides `stalinsort` functionality
pub trait Stalinsort {
/// **Stalinsort** is a single pass stable (technically) sorting algorithm
/// that removes out of order items.
fn stalinsort(&mut self);
}

impl<T: PartialOrd> Stalinsort for Vec<T> {
fn stalinsort(&mut self) {
let mut index: usize = 1;

while index < self.len() {
if self[index] < self[index-1] {
// This item is not great enough. Send it away.
self.remove(index);
} else {
// This item has been approved by the commissar. Next!
index += 1
}
}
}
}
29 changes: 29 additions & 0 deletions tests/stalin_sorting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
extern crate sorting;

use sorting::*;

#[test]
fn does_not_remove_in_order_list() {
let mut sorted_vector = vec![1,2,3,4,5];

sorted_vector.stalinsort();

assert_eq!(sorted_vector, vec![1,2,3,4,5])
}

#[test]
fn removes_all_items_except_first_if_reverse_ordered() {
let mut vector = vec![5,4,3,2,1];

vector.stalinsort();

assert_eq!(vector, vec![5])
}

#[test]
fn removes_out_of_order_items() {
let mut vector = vec![1,2,5,4,6];
vector.stalinsort();

assert_eq!(vector, vec![1,2,5,6])
}