Merge Sorted Sequences With Peekable
Merge two sorted slices with peekable iterators: peek compares the front runners without consuming, next advances the loser, and remainders drain at the end.
Code
fn merge_sorted(a: &[i32], b: &[i32]) -> Vec<i32> {
let mut it_a = a.iter().peekable();
let mut it_b = b.iter().peekable();
let mut out = Vec::with_capacity(a.len() + b.len());
// peek 只看不取,next 才前进:每次取两路队首较小者
while let (Some(&x), Some(&y)) = (it_a.peek(), it_b.peek()) {
if x <= y {
out.push(*it_a.next().expect("peeked"));
} else {
out.push(*it_b.next().expect("peeked"));
}
}
// 一路耗尽后剩余尾部直接并入(迭代器本身已有序)
out.extend(it_a);
out.extend(it_b);
out
}
fn main() {
let merged = merge_sorted(&[1, 4, 9], &[2, 3, 10]);
println!("{merged:?}");
println!("one empty: {:?}", merge_sorted(&[], &[7]));
println!("both drain: {:?}", merge_sorted(&[5], &[1, 2, 3]));
}How the snippet works
Merge Sorted Sequences With Peekable keeps everything in the functions merge_sorted and main.
Repetition is confined to while let (Some(&x), Some(&y)) = (it_a.peek(), it_b.peek()) — the rest of the file is straight-line.
Applying it
The main signature reads fn merge_sorted(a: &[i32], b: &[i32]) -> Vec<i32>
Output lines are prefixed (one empty:, both drain:), making each step’s effect easy to spot.
The sequence merge_sorted lives in main; running the file triggers it.
Statements that matter
while let (Some(&x), Some(&y)) = (it_a.peek(), it_b.peek()) {
if x <= y {
out.push(*it_a.next().expect("peeked"));
} else {
out.push(*it_b.next().expect("peeked"));
}
}
let mut it_a = a.iter().peekable();
let mut it_b = b.iter().peekable();
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Merge Sorted Sequences With Peekable print when run?
- Invoke the file as-is — the `one empty:`, `both drain:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.