One problem I see with the code is when the two arrays do not have same length. In either case of (array1.length > array2.length or reverse) the remaining elements of longer array will not be processed. So if you add a more code at end of this the loops to deal with that case, this might work well!
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
List<Integer> mergedArray = new ArrayList<>();
int counter = 0, i = 0, j = 0;
for (i = 0; i < array1.size(); i++) {
for (j = counter; j < array2.size(); j++) {
if (array1.get(i) > array2.get(j)) {
mergedArray.add(array2.get(j));
counter++;
} else {
mergedArray.add(array1.get(i));
System.out.println("i " +i);
break;
}
}
}
// More code here
if (j==array2.size()){//copy rest of array1 into mergedArray}
if (i==array1.size()){//copy rest of array2 into mergedArray}
return mergedArray;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…