From 1208a6b042e60bac6be6257047c7acb928afd948 Mon Sep 17 00:00:00 2001 From: opixelum <48217573+opixelum@users.noreply.github.com> Date: Thu, 7 Dec 2023 01:47:03 +0100 Subject: [PATCH] Implement merge sort in Rust --- rust/src/sorting.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/rust/src/sorting.rs b/rust/src/sorting.rs index 92c5ae3..91e4d37 100644 --- a/rust/src/sorting.rs +++ b/rust/src/sorting.rs @@ -1,3 +1,5 @@ +use crate::arrays::{copy_arrays, merge_arrays}; + pub fn insertion_sort(array: &mut [T]) { let size = array.len(); @@ -81,6 +83,22 @@ pub fn cocktail_sort(array: &mut [T]) { } } +pub fn merge_sort(array: &mut [T]) { + let len = array.len(); + if len > 1 { + let middle = array.len() / 2; + let (left, right) = array.split_at_mut(middle); + + merge_sort(left); + merge_sort(right); + + let mut temp = vec![left[0].clone(); len]; + merge_arrays(left, right, &mut temp); + + copy_arrays(&temp, array); + } +} + #[cfg(test)] mod tests { use super::*; @@ -198,4 +216,29 @@ mod tests { SORTED_STRING_ARRAY.iter().map(|&s| s.into()).collect(); assert_eq!(string_array, sorted_string_array); } + + #[test] + fn test_merge_sort() { + let mut int_array = INT_ARRAY; + merge_sort(&mut int_array); + assert_eq!(int_array, SORTED_INT_ARRAY); + + let mut float_array = FLOAT_ARRAY; + merge_sort(&mut float_array); + assert_eq!(float_array, SORTED_FLOAT_ARRAY); + + let mut char_array = CHAR_ARRAY; + merge_sort(&mut char_array); + assert_eq!(char_array, SORTED_CHAR_ARRAY); + + let mut string_slice_array = STRING_SLICE_ARRAY; + merge_sort(&mut string_slice_array); + assert_eq!(string_slice_array, SORTED_STRING_SLICE_ARRAY); + + let mut string_array: Vec = STRING_ARRAY.iter().map(|&s| s.into()).collect(); + merge_sort(&mut string_array); + let sorted_string_array: Vec = + SORTED_STRING_ARRAY.iter().map(|&s| s.into()).collect(); + assert_eq!(string_array, sorted_string_array); + } }