-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertNumber.java
More file actions
36 lines (31 loc) · 943 Bytes
/
InsertNumber.java
File metadata and controls
36 lines (31 loc) · 943 Bytes
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
import java.util.*;
public class InsertNumber {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80, 90, 100));
insertUsingIteration(list, 55);
insertUsingBinarySearch(list, 55);
System.out.println("Result: " + list);
}
public static void insertUsingIteration(ArrayList<Integer> list, int num) {
int indx = -1;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) > num) {
indx = i;
break;
}
}
list.add(indx, num);
}
public static void insertUsingBinarySearch(List<Integer> list, int number) {
int position = findPosition(list, 0, list.size() - 1, number);
list.add(position, number);
}
public static int findPosition(List<Integer> list, int start, int end, int num) {
int mid = (start + end) / 2;
if (list.get(end) < num)
findPosition(list, start, end, num);
else
return mid + 1;
return -1;
}
}