Math Fundamentals18 sections · 814 units
Open in Course

Search Insert - Implementation (The code)

Binary search solution

Here's the binary search solution:


function searchInsert(nums, target)
    left := 0
    right := length of nums - 1
    while left  right
        mid := left + (right - left) / 2
        if nums[mid] = target then
            return mid
        else if nums[mid] < target then
            left := mid + 1
        else
            right := mid - 1
    return left

You maintain a search range [left,right][left, right]. At each step, you check the middle element. If it matches, return the index. Otherwise, move leftleft or rightright to search the appropriate half. When the loop ends, leftleft is the insertion position.