My teacher wants me to add an Integer item one at a time to a generic arraylist inside MySortedArray Class. I have to add 1_000_000 items. The custom add method he wants me to implement in MySortedArray, needs to add able to sort the arraylist after every addition. However, sorting it a million times after every add() call is too slow. What am I supposed to do? I need to be able to find the index in the ArrayList where I should add the Integer item very quickly. Would binary search work?
@Test
void testRandomInts() {
MySortedArray<Integer> ints = new MySortedArray<>(10);
for (int i = 0; i < 200; i++) {
int num = (int)(Math.random() * 10 + 1);
ints.add(num);
}
System.out.println("array is: " + ints.contents.toString());
assertTrue(isSorted(ints));
}