algo/src/algorithms/mergesort.rs
Jan Christian Grünhage 62f1b27dff refactor: cargo fmt
2017-08-27 17:26:01 +02:00

61 lines
1.8 KiB
Rust

use algorithms::Algorithm;
pub struct Mergesort;
impl Algorithm for Mergesort {
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 Mergesort::sort(vector) {
Ok(v) => v,
Err(e) => return Err(e),
};
second = match Mergesort::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);
}
}
}