forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.rs
79 lines (69 loc) · 1.91 KB
/
merge_sort.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
fn merge<T: Ord + Copy>(arr: &mut [T], mid: usize) {
// Create temporary vectors to support the merge.
let left_half = arr[..mid].to_vec();
let right_half = arr[mid..].to_vec();
// Indexes to track the positions while merging.
let mut l = 0;
let mut r = 0;
for v in arr {
// Choose either the smaller element, or from whichever vec is not exhausted.
if r == right_half.len() || (l < left_half.len() && left_half[l] < right_half[r]) {
*v = left_half[l];
l += 1;
} else {
*v = right_half[r];
r += 1;
}
}
}
pub fn merge_sort<T: Ord + Copy>(arr: &mut [T]) {
if arr.len() > 1 {
let mid = arr.len() / 2;
// Sort the left half recursively.
merge_sort(&mut arr[..mid]);
// Sort the right half recursively.
merge_sort(&mut arr[mid..]);
// Combine the two halves.
merge(arr, mid);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic() {
let mut res = vec![10, 8, 4, 3, 1, 9, 2, 7, 5, 6];
merge_sort(&mut res);
assert_eq!(res, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
}
#[test]
fn basic_string() {
let mut res = vec!["a", "bb", "d", "cc"];
merge_sort(&mut res);
assert_eq!(res, vec!["a", "bb", "cc", "d"]);
}
#[test]
fn empty() {
let mut res = Vec::<u8>::new();
merge_sort(&mut res);
assert_eq!(res, vec![]);
}
#[test]
fn one_element() {
let mut res = vec![1];
merge_sort(&mut res);
assert_eq!(res, vec![1]);
}
#[test]
fn pre_sorted() {
let mut res = vec![1, 2, 3, 4];
merge_sort(&mut res);
assert_eq!(res, vec![1, 2, 3, 4]);
}
#[test]
fn reverse_sorted() {
let mut res = vec![4, 3, 2, 1];
merge_sort(&mut res);
assert_eq!(res, vec![1, 2, 3, 4]);
}
}