Created
October 23, 2015 19:11
-
-
Save arnauorriols/10d752e8feef84d810c8 to your computer and use it in GitHub Desktop.
Merge-sort implementation in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn mergesort(unsorted: &[u32]) -> Vec<u32> { | |
let n = unsorted.len(); | |
if n < 2 { | |
return unsorted.to_vec(); | |
} | |
let sorted_child1 = mergesort(&unsorted[..n/2]); | |
let sorted_child2 = mergesort(&unsorted[n/2..]); | |
let mut ptr1 = 0; | |
let mut ptr2 = 0; | |
let mut sorted = vec![]; | |
for _ in 0..n { | |
if ptr1 >= sorted_child1.len() { | |
sorted.push(sorted_child2[ptr2]); | |
ptr2 += 1; | |
} else if ptr2 >= sorted_child2.len() { | |
sorted.push(sorted_child1[ptr1]); | |
ptr1 += 1; | |
} else if sorted_child1[ptr1] <= sorted_child2[ptr2] { | |
sorted.push(sorted_child1[ptr1]); | |
ptr1 += 1; | |
} else { | |
sorted.push(sorted_child2[ptr2]); | |
ptr2 += 1; | |
} | |
} | |
sorted | |
} | |
#[test] | |
fn test_mergesort() { | |
let unsorted_array = [3, 7, 2, 5, 9, 1, 5, 7, 2, 98, 32, 6, 4]; | |
assert_eq!(vec![1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 9, 32, 98], mergesort(&unsorted_array)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment