-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertIndexinSortedArray.java
More file actions
48 lines (41 loc) · 1.39 KB
/
Copy pathInsertIndexinSortedArray.java
File metadata and controls
48 lines (41 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.*;
public class InsertIndexinSortedArray {
public static void main(String[] args) {
// Create an array of integers
int[] nums = {1, 2, 4, 5, 6};
int target = 5;
// target = 0;
// target = 7;
// Call the searchInsert function and print the result
System.out.print(searchInsert(nums, target));
}
public static int searchInsert(int[] nums1, int target) {
// Check if the input array is empty or null
if (nums1 == null || nums1.length == 0) {
return 0;
}
// Initialize variables for binary search
int start = 0;
int end = nums1.length - 1;
int mid = start + (end - start) / 2;
while (start + 1 < end) {
mid = start + (end - start) / 2;
// Compare the middle element with the target
if (nums1[mid] == target) {
return mid;
} else if (nums1[mid] > target) {
end = mid;
} else {
start = mid;
}
}
// Determine the insertion position based on binary search results
if (nums1[start] >= target) {
return start;
} else if (nums1[start] < target && target <= nums1[end]) {
return end;
} else {
return end + 1;
}
}
}