algo/src/sorting/merge.rs

61 lines
1.8 KiB
Rust
Raw Permalink Normal View History

use sorting::Algorithm;
2017-08-27 13:51:31 +00:00
pub struct Sort;
2017-08-27 13:51:31 +00:00
impl Algorithm for Sort {
2017-08-27 13:51:31 +00:00
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) {
2017-08-27 13:51:31 +00:00
Ok(v) => v,
2017-08-27 15:26:01 +00:00
Err(e) => return Err(e),
2017-08-27 13:51:31 +00:00
};
second = match Sort::sort(second) {
2017-08-27 13:51:31 +00:00
Ok(v) => v,
2017-08-27 15:26:01 +00:00
Err(e) => return Err(e),
2017-08-27 13:51:31 +00:00
};
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);
}
}
2017-08-27 15:26:01 +00:00
}