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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to merge two vectors in Rust

1 Answer

0 votes
use std::vec::Vec;

fn print_vector(vec: &Vec<i32>) {
    for &value in vec {
        print!("{} ", value);
    }
}

fn merge_two_vectors_into_one(num1: &Vec<i32>, num2: &Vec<i32>) -> Vec<i32> {
    let mut numbers = Vec::with_capacity(num1.len() + num2.len());
    let (mut i, mut j) = (0, 0);

    while i < num1.len() && j < num2.len() {
        if num1[i] <= num2[j] {
            numbers.push(num1[i]);
            i += 1;
        } else {
            numbers.push(num2[j]);
            j += 1;
        }
    }

    while i < num1.len() {
        numbers.push(num1[i]);
        i += 1;
    }

    while j < num2.len() {
        numbers.push(num2[j]);
        j += 1;
    }

    numbers
}

fn main() {
    let num1 = vec![7, 3, 2, 9, 1];
    let num2 = vec![5, 8, 6, 4, 0, 11, 10, 12];

    let numbers = merge_two_vectors_into_one(&num1, &num2);

    print_vector(&numbers);
}


    
/*
run:

5 7 3 2 8 6 4 0 9 1 11 10 12 
  
*/

 



answered Oct 9, 2024 by avibootz
...