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.

RustData Integrity

Code

rustsnippet
25 lines
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

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.