Merge sort
Split the sequence into smaller parts until each part is sorted. Merge two sorted parts by repeatedly taking their smaller front item.
Simple example
First sort the pairs into 1,3 and 2,4. Compare their front values and print the merged result.
fn main() {
let mut values: [i64; 4] = [3, 1, 2, 4];
let mut merged: [i64; 4] = [0, 0, 0, 0];
let mut width: i64 = 1;
while width < 4 {
let mut start: i64 = 0;
while start < 4 {
let mut left: i64 = start;
let middle: i64 = (start + width);
let mut right: i64 = middle;
let limit: i64 = (middle + width);
let mut pos: i64 = start;
while pos < limit {
if (left < middle && (right >= limit || values[(left) as usize] <= values[(right) as usize])) {
merged[(pos) as usize] = values[(left) as usize];
left += 1;
} else {
merged[(pos) as usize] = values[(right) as usize];
right += 1;
}
pos += 1;
}
start = limit;
}
let mut i: i64 = 0;
while i < 4 {
values[(i) as usize] = merged[(i) as usize];
i += 1;
}
width *= 2;
}
let mut i: i64 = 0;
while i < 4 {
println!("{}", values[(i) as usize]);
i += 1;
}
}
1 2 3 4
Everyday examples
Combine two ticket desks
Desk A has tickets 1 and 6. Desk B has 2 and 4. What is the merged order?
Compare the two fronts. When B is empty, copy A’s remaining ticket.
Merge two dated diaries
Both diaries have a day-5 entry. How can the left diary keep precedence for ties?
Choose from the left diary first when dates compare equal. This preserves the prior order.
Combine an empty batch
One folder has no reports. The other has reports 3 and 9 in order. What work remains?
Copy the remaining reports directly. There is no pair of fronts to compare.
Cost and limits
Merge sort takes O(n log n) time. A typical array implementation needs extra space for the merged values.