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 . At each step, you check the middle element. If it matches, return the index. Otherwise, move or to search the appropriate half. When the loop ends, is the insertion position.