```
public class Solution {
public int searchInsert(int[] nums, int target) {
int low = 0;
int high = nums.length-1;
while (low < high) {
int mid = (low+high+1)/2; // rounding up to avoid infinite loop when the array has 2 elements
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
low = mid;
} else {
high = mid-1;
}
}
if (nums[low] < target) {
return low+1;
}
return low;
}
}
```