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,845 questions

51,766 answers

573 users

How to search insert position of K in a sorted vector with Rust

2 Answers

0 votes
// Given a sorted array/vector/list of distinct integers and a target value K, 
// return the index if the target is found. 
// If not, return the index where it would be if it were inserted in order.

fn search_insert_position_of_k(vec: &[i32], k: i32) -> usize {
    let mut left = 0;
    let mut right = vec.len() as isize - 1;

    // Function to find the index of k or the position - Using Binary Search
    while left <= right {
        let mid = left + (right - left) / 2;

        if vec[mid as usize] == k {
            return mid as usize;
        } else if vec[mid as usize] > k {
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }

    left as usize
}

fn main() {
    let vec1 = vec![1, 3, 5, 6, 7, 8];
    let k1 = 5;
    println!("{}", search_insert_position_of_k(&vec1, k1));

    let vec2 = vec![1, 3, 5, 6, 7, 8];
    let k2 = 2;
    println!("{}", search_insert_position_of_k(&vec2, k2));

    let vec3 = vec![1, 3, 5, 6, 7, 8];
    let k3 = 9;
    println!("{}", search_insert_position_of_k(&vec3, k3));
}

 
 
/*
run:
 
2
1
6

*/

 



answered May 10, 2025 by avibootz
0 votes
// Given a sorted array/vector/list of distinct integers and a target value K, 
// return the index if the target is found. 
// If not, return the index where it would be if it were inserted in order.

fn search_insert_position_of_k(vec: &[i32], k: i32) -> usize {
    for (i, &val) in vec.iter().enumerate() {
        // If k is found or needs to be inserted before val
        if val >= k {
            return i;
        }
    }
    // If k is greater than all elements, it should be inserted at the end
    vec.len()
}

fn main() {
    let vec1 = vec![1, 3, 5, 6, 7, 8];
    let k1 = 5;
    println!("{}", search_insert_position_of_k(&vec1, k1));

    let vec2 = vec![1, 3, 5, 6, 7, 8];
    let k2 = 2;
    println!("{}", search_insert_position_of_k(&vec2, k2));

    let vec3 = vec![1, 3, 5, 6, 7, 8];
    let k3 = 9;
    println!("{}", search_insert_position_of_k(&vec3, k3));
}

 
 
/*
run:
 
2
1
6

*/

 



answered May 10, 2025 by avibootz
...