Last active
August 29, 2015 14:08
-
-
Save jakejscott/d6d6cdf7a488f5da1eb1 to your computer and use it in GitHub Desktop.
Merge sort ported from the C# example
This file contains hidden or 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 main() { | |
let list: Vec<u64> = vec![1, 2, 3, 6, 8, 8, 4, 5, 99, 234, 4, 1, 2, 45]; | |
let sorted = sort(list); | |
println!("sorted: {}", sorted); | |
// sorted: [1, 1, 2, 2, 3, 4, 4, 5, 6, 8, 8, 45, 99, 234] | |
} | |
fn sort<T: Clone + PartialOrd>(list: Vec<T>) -> Vec<T> { | |
if list.len() <= 1 { | |
return list; | |
} | |
let left_slice = list.slice(0u, list.len() / 2); | |
let right_slice = list.slice(left_slice.len(), list.len()); | |
let mut left: Vec<T> = Vec::with_capacity(left_slice.len()); | |
let mut right: Vec<T> = Vec::with_capacity(right_slice.len()); | |
left.push_all(left_slice); | |
right.push_all(right_slice); | |
return merge(&mut sort(left), &mut sort(right)); | |
} | |
fn merge<T: PartialOrd + Clone>(left: &mut Vec<T>, right: &mut Vec<T>) -> Vec<T> { | |
let mut result: Vec<T> = Vec::with_capacity(left.len() + right.len()); | |
while left.len() > 0 && right.len() > 0 { | |
if left[0] <= right[0] { | |
result.push(left[0].clone()); | |
left.remove(0u); | |
} else { | |
result.push(right[0].clone()); | |
right.remove(0u); | |
} | |
} | |
result.push_all(left.as_slice()); | |
result.push_all(right.as_slice()); | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment