algo/src/sorting/quick.rs
Jan Christian Grünhage 198e154495 feat: demo all algorithms
Add demo code for all currently implemented algorithms, as well as a refactoring of the package structure.
Rename of the mistakenly called insertion sort, which was actually selection sort.

Fixes #1 and Fixes #2
2017-08-29 10:08:42 +02:00

60 lines
1.5 KiB
Rust

use sorting::Algorithm;
pub struct Sort;
impl Algorithm for Sort {
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 Sort::sort(smaller) {
Ok(v) => v,
Err(e) => return Err(e),
}
{
result.push(v);
}
for v in pivots {
result.push(v);
}
for v in match Sort::sort(larger) {
Ok(v) => v,
Err(e) => return Err(e),
}
{
result.push(v);
}
return Ok(result);
}
}