-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertIndexInSortedArray.java
More file actions
55 lines (50 loc) · 1.44 KB
/
InsertIndexInSortedArray.java
File metadata and controls
55 lines (50 loc) · 1.44 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
49
50
51
52
53
54
55
package algorithm.search;
/**
* The type Insert index in sorted array.
*/
public class InsertIndexInSortedArray {
/**
* Insert position int.
* This will only work if element is only present.
*
* @param arr the arr
* @param target the target
* @return the int
*/
public static int insertPosition(int[] arr, int target) {
int arrSize = arr.length;
int start = 0, end = arrSize - 1;
int mid = 0, pos = 0;
while (start <= end) {
mid = start + (end - start) / 2;
if (arr[mid] == target)
return target;
//if mid value greater than target serach in the left half
else if (arr[mid] > target) {
end = mid - 1;
pos = mid;
}
//otherwise search in the right half
else {
start = mid + 1;
pos = mid + 1;
}
}
return pos;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[])
{
int[]arr = {0, 1, 2, 3, 5, 6};
// Example 1
System.out.println("Index to Insert " + "\"5\" is " + insertPosition(arr, 5));
// Example 2
System.out.println("Index to Insert " + "\"3\" is " + insertPosition(arr, 3));
// Example 3
System.out.println("Index to Insert " + "\"7\" is " + insertPosition(arr, 7));
}
}