From b607608b855b3fd31c36ca5ef4ad367d90a22770 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Christian=20Gr=C3=BCnhage?= Date: Sun, 27 Aug 2017 18:52:51 +0200 Subject: [PATCH] feat: add quicksort --- src/algorithms/mod.rs | 1 + src/algorithms/quicksort.rs | 59 +++++++++++++++++++++++++++++++++++++ src/main.rs | 4 +-- 3 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 src/algorithms/quicksort.rs diff --git a/src/algorithms/mod.rs b/src/algorithms/mod.rs index ab5e21e..9d48bae 100644 --- a/src/algorithms/mod.rs +++ b/src/algorithms/mod.rs @@ -6,3 +6,4 @@ pub trait Algorithm { pub mod bubblesort; pub mod mergesort; pub mod insertionsort; +pub mod quicksort; diff --git a/src/algorithms/quicksort.rs b/src/algorithms/quicksort.rs new file mode 100644 index 0000000..71c9a75 --- /dev/null +++ b/src/algorithms/quicksort.rs @@ -0,0 +1,59 @@ +use algorithms::Algorithm; + +pub struct Quicksort; + +impl Algorithm for Quicksort { + fn sort(mut vector: Vec) -> Result, &'static str> { + let pivot = match vector.pop() { + Some(v) => v, + None => return Ok(Vec::new()), + }; + let mut pivots: Vec = Vec::new(); + pivots.push(pivot); + + let mut smaller: Vec = Vec::new(); + let mut larger: Vec = Vec::new(); + + while vector.len() != 0 { + let element = match vector.pop() { + Some(v) => v, + None => { + return Err( + "Vector had a length not equal to 0, but still had no more element in it. This point should not be reachable.", + ) + } + }; + if element < pivot { + smaller.push(element); + } else if element > pivot { + larger.push(element); + } else { + pivots.push(element); + } + } + + let mut result: Vec = Vec::new(); + + for v in match Quicksort::sort(smaller) { + Ok(v) => v, + Err(e) => return Err(e), + } + { + result.push(v); + } + + for v in pivots { + result.push(v); + } + + for v in match Quicksort::sort(larger) { + Ok(v) => v, + Err(e) => return Err(e), + } + { + result.push(v); + } + + return Ok(result); + } +} diff --git a/src/main.rs b/src/main.rs index 5c63f76..9568228 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,11 @@ mod algorithms; -use algorithms::insertionsort::Insertionsort; +use algorithms::quicksort::Quicksort; use algorithms::Algorithm; fn main() { let unsorted: Vec = vec![2498, 29687, 24, 5, 94545, 8, 51, 152, 48, 871, 5]; - let sorted = match Insertionsort::sort(unsorted) { + let sorted = match Quicksort::sort(unsorted) { Ok(v) => v, Err(e) => { println!("Something went wrong! {}", e);