Say I have a sorted list (in ascending order) like thisArrayList<Integer> arr = Arrays.asList(1, 2, 3, 5, 6). There will be no duplicates in the list.
I want to add an integer to it at the correct index so that the array is still sorted after I add the element, like so: arr.add(4) // now arr = {1, 2, 3, 4, 5, 6}.
How do I achieve this elegantly WITHOUT resorting to sorting AFTER I add the element by using Collections.sort(arr) or something.
I'm looking for a better/more elegant solution than the one I currently have (I don't even know if it works for all cases lol):
int n = 4 // number I want to add to the list
boolean added = false;
for(int i < 0; i < arr.size(); i++) {
if(n < arr.get(i)) {
arr.add(i, n)
added = true;
break;
}
}
if(added == false) {
arr.add(n)
}
Thanks for the help in advance!