Search Insert Position in Rust

impl Solution {
    fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
        // Initialize start and end pointers as usize for indexing the vector
        let mut start = 0 as usize;
        let mut end = nums.len() as usize; // Note: 'end' is exclusive

        // Loop for binary search. Continues as long as 'start' is less than 'end'
        while start < end {
            // Calculate the mid index to avoid integer overflow
            // This is a safer way to calculate the middle of 'start' and 'end'
            let mid = start + (end - start) / 2;

            // Compare the element at 'mid' index with the target
            if nums[mid] == target {
                // If the element at 'mid' is the target, return 'mid' as the index
                return mid as i32;
            }

            // If the element at 'mid' is less than the target, adjust 'start'
            // This narrows the search to the right half of the current segment
            if nums[mid] < target {
                start = mid + 1;
            } else {
                // Else, adjust 'end' to 'mid'
                // This narrows the search to the left half of the current segment
                end = mid;
            }
        }

        // If the target is not found, 'start' will be at the insertion position
        // This is where the target should be inserted to maintain sorted order
        start as i32
    }
}

PrevNext