Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,562 questions

56,777 answers

573 users

How to rearrange an array into a zig-zag pattern (a < b > c < d > e < f > g) in Rust

2 Answers

0 votes
// This program rearranges an array into a zig-zag pattern, where the elements 
// alternate between being smaller and larger than their neighbors

// a < b > c < d > e < f > g...
// 3 < 5 > 1 < 9 > 6 < 7 > 2 < 4

fn rearrange_into_zigzag(arr: &mut [i32]) {
    for i in 0..arr.len().saturating_sub(1) {
        if i % 2 == 0 {
            // Expect arr[i] < arr[i + 1]
            if arr[i] > arr[i + 1] {
                arr.swap(i, i + 1);
            }
        } else {
            // Expect arr[i] > arr[i + 1]
            if arr[i] < arr[i + 1] {
                arr.swap(i, i + 1);
            }
        }
    }
}

fn main() {
    let mut arr = [3, 5, 1, 7, 9, 6, 4, 2];

    rearrange_into_zigzag(&mut arr);

    println!("{arr:?}");
}

    
/*
run:

[3, 5, 1, 9, 6, 7, 2, 4]

*/

 



answered Oct 8 by avibootz
edited Oct 8 by avibootz
0 votes
// This program rearranges an array into a zig-zag pattern, where the elements 
// alternate between being smaller and larger than their neighbors

// a < b > c < d > e < f > g...
// 3 < 5 > 1 < 9 > 6 < 7 > 2 < 4
    
fn rearrange_into_zigzag(arr: &mut [i32]) {
    for i in 0..arr.len().saturating_sub(1) {
        let should_swap =
            (i % 2 == 0 && arr[i] > arr[i + 1]) ||
            (i % 2 == 1 && arr[i] < arr[i + 1]);

        if should_swap {
            arr.swap(i, i + 1);
        }
    }
}

fn main() {
    let mut arr = [3, 5, 1, 7, 9, 6, 4, 2];

    rearrange_into_zigzag(&mut arr);

    println!("{arr:?}");
}

    
/*
run:

[3, 5, 1, 9, 6, 7, 2, 4]

*/

 



answered Oct 8 by avibootz

Related questions

...