feat: add quicksort

This commit is contained in:
Jan Christian Grünhage 2017-08-27 18:52:51 +02:00
parent 15d253d49c
commit b607608b85
3 changed files with 62 additions and 2 deletions

View file

@ -6,3 +6,4 @@ pub trait Algorithm {
pub mod bubblesort;
pub mod mergesort;
pub mod insertionsort;
pub mod quicksort;

View file

@ -0,0 +1,59 @@
use algorithms::Algorithm;
pub struct Quicksort;
impl Algorithm for Quicksort {
fn sort(mut vector: Vec<i32>) -> Result<Vec<i32>, &'static str> {
let pivot = match vector.pop() {
Some(v) => v,
None => return Ok(Vec::new()),
};
let mut pivots: Vec<i32> = Vec::new();
pivots.push(pivot);
let mut smaller: Vec<i32> = Vec::new();
let mut larger: Vec<i32> = 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<i32> = 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);
}
}

View file

@ -1,11 +1,11 @@
mod algorithms;
use algorithms::insertionsort::Insertionsort;
use algorithms::quicksort::Quicksort;
use algorithms::Algorithm;
fn main() {
let unsorted: Vec<i32> = 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);