diff --git a/src/algorithms/bubblesort.rs b/src/algorithms/bubblesort.rs index 83b2303..0c11e98 100644 --- a/src/algorithms/bubblesort.rs +++ b/src/algorithms/bubblesort.rs @@ -3,7 +3,7 @@ use algorithms::Algorithm; pub struct Bubblesort; impl Algorithm for Bubblesort { - fn sort(mut vector: Vec) -> Vec { + fn sort(mut vector: Vec) -> Result, &'static str> { for i in 0..(vector.len()) { for j in 0..(vector.len() - i - 1) { if vector[j] > vector[j + 1] { @@ -13,6 +13,6 @@ impl Algorithm for Bubblesort { } } } - return vector; + return Ok(vector); } } \ No newline at end of file diff --git a/src/algorithms/mergesort.rs b/src/algorithms/mergesort.rs new file mode 100644 index 0000000..58a1794 --- /dev/null +++ b/src/algorithms/mergesort.rs @@ -0,0 +1,60 @@ +use algorithms::Algorithm; + +pub struct Mergesort; + +impl Algorithm for Mergesort { + fn sort(mut vector: Vec) -> Result, &'static str> { + if vector.len() == 1 { + return Ok(vector); + } else { + let mut second: Vec = 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 = 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); + } + } +} \ No newline at end of file diff --git a/src/algorithms/mod.rs b/src/algorithms/mod.rs index 7f79440..ab03803 100644 --- a/src/algorithms/mod.rs +++ b/src/algorithms/mod.rs @@ -1,6 +1,7 @@ pub trait Algorithm { - fn sort(vector: Vec) -> Vec; + fn sort(vector: Vec) -> Result, &'static str>; } -pub mod bubblesort; \ No newline at end of file +pub mod bubblesort; +pub mod mergesort; \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 352be4d..5782b24 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,16 @@ mod algorithms; -use algorithms::bubblesort::Bubblesort; +use algorithms::mergesort::Mergesort; use algorithms::Algorithm; fn main() { let unsorted : Vec = vec![2498,29687,24,5,94545,8,51,152,48,871,5]; - let sorted = Bubblesort::sort(unsorted); + let sorted = match Mergesort::sort(unsorted) { + Ok(v) => v, + Err(e) => { + println!("Something went wrong! {}", e); + return; + } + }; println!("{:?}", sorted); } \ No newline at end of file