algo/src/sorting/merge.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

61 lines
1.8 KiB
Rust

use sorting::Algorithm;
pub struct Sort;
impl Algorithm for Sort {
fn sort(mut vector: Vec<i32>) -> Result<Vec<i32>, &'static str> {
if vector.len() == 1 {
return Ok(vector);
} else {
let mut second: Vec<i32> = Vec::new();
let length = vector.len();
for _ in 0..length / 2 {
second.push(match vector.pop() {
Some(v) => v,
None => {
return Err("Error during splitting the vector.");
}
});
}
let first = match Sort::sort(vector) {
Ok(v) => v,
Err(e) => return Err(e),
};
second = match Sort::sort(second) {
Ok(v) => v,
Err(e) => return Err(e),
};
let mut result: Vec<i32> = Vec::new();
let first_length = first.len();
let second_length = second.len();
let mut first_index = 0;
let mut second_index = 0;
while first_index < first_length && second_index < second_length {
if first[first_index] < second[second_index] {
result.push(first[first_index]);
first_index += 1;
} else {
result.push(second[second_index]);
second_index += 1;
}
}
while first_index < first_length {
result.push(first[first_index]);
first_index += 1;
}
while second_index < second_length {
result.push(second[second_index]);
second_index += 1;
}
return Ok(result);
}
}
}