search insert position
Typer | Posted on | |
public class SearchInsertPosition {
// Returns the index of target, or the index where it should be inserted
public static int searchInsert(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
// Example test cases using values between 11 and 20
public static void main(String[] args) {
int[] example1 = {11, 13, 15, 16}; // target = 15 → exists
int[] example2 = {11, 13, 15, 16}; // target = 12 → insert at 1
int[] example3 = {12, 14, 16, 18}; // target = 19 → insert at end
int[] example4 = {12, 14, 16, 18}; // target = 10 → insert at start
int[] example5 = {13, 14, 16, 18}; // target = 14 → exists at 1
System.out.println("Example 1: Output = " + searchInsert(example1, 15)); // Output: 2
System.out.println("Example 2: Output = " + searchInsert(example2, 12)); // Output: 1
System.out.println("Example 3: Output = " + searchInsert(example3, 19)); // Output: 4
System.out.println("Example 4: Output = " + searchInsert(example4, 10)); // Output: 0
System.out.println("Example 5: Output = " + searchInsert(example5, 14)); // Output: 1
}
}