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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
pub fn mergesort(arr: &mut [i32]) {
let mid = arr.len() / 2;
if mid == 0 {
return;
}
mergesort(&mut arr[..mid]);
mergesort(&mut arr[mid..]);
let mut ret = arr.to_vec();
merge(&arr[..mid], &arr[mid..], &mut ret[..]);
arr.copy_from_slice(&ret);
}
pub fn mergesort_bottom_up(arr: &mut [i32]) {
let mut width = 1;
let mut ret = arr.to_vec();
let len = arr.len();
while width < len {
let mut i = 0;
while i < len {
let upper = ::std::cmp::min(i + 2 * width, len);
let mid = ::std::cmp::min(i + width, len);
merge(&arr[i..mid], &arr[mid..upper], &mut ret[i..upper]);
arr[i..upper].copy_from_slice(&ret[i..upper]);
i += 2 * width;
}
width *= 2;
}
}
fn merge(arr1: &[i32], arr2: &[i32], ret: &mut [i32]) {
let mut left = 0;
let mut right = 0;
let mut index = 0;
while left < arr1.len() && right < arr2.len() {
if arr1[left] <= arr2[right] {
ret[index] = arr1[left];
index += 1;
left += 1;
} else {
ret[index] = arr2[right];
index += 1;
right += 1;
}
}
if left < arr1.len() {
ret[index..].copy_from_slice(&arr1[left..]);
}
if right < arr2.len() {
ret[index..].copy_from_slice(&arr2[right..]);
}
}
#[cfg(test)]
mod base {
use super::*;
base_cases!(mergesort);
}
#[cfg(test)]
mod bottom_up {
use super::*;
base_cases!(mergesort_bottom_up);
}