DEV Community

Discussion on: Daily Challenge #308 - Wave Sort

Collapse
 
qm3ster profile image
Mihail Malo • Edited

Rust

use itertools::Itertools;
fn wave(nums: &mut [u32]) -> impl Iterator<Item = u32> + '_ {
    nums.sort_unstable();
    let (small, big) = nums.split_at(nums.len() / 2);
    big.iter().interleave(small).copied()
}
Enter fullscreen mode Exit fullscreen mode

Mutates your slice to sort. Don't want it sorted? Clone it yourself!
Doesn't actually verify if successful, since by <= >= rules this can never fail. This enables us to return an iterator with confidence instead of having to collect.
And integer division means that with odd length input the right "half" (greater numbers) will be longer, so we can start with greater numbers as per rules.

fn main() {
    let mut cases: [&mut [u32]; 3] = [
        &mut [1, 2, 34, 4, 5, 5, 5, 65, 6, 65, 5454, 4],
        &mut [3, 2, 5, 1, 6],
        &mut [1, 2, 3],
    ];
    for nums in &mut cases {
        println!("{:?}", wave(nums).collect::<Vec<_>>());
    }
}
Enter fullscreen mode Exit fullscreen mode

Look at it go!