You should not modify the indices while you iterate over the array, else you will see some weird result. The iteration would certainly skip some elements, as their indices are not the one that is supposed to be.
Suppose you are iterating the array like this:
0 1 2 3 4 5 // indices
1 2 5 6 7 8 // array elements
^
i // current position of i
Now you remove the element at index 0
. Then all the remaining elements will shift left, but i
will keep on moving forward. After deleting element at index 0, the array structure is like this:
0 1 2 3 4 // indices
2 5 6 7 8 // array elements
^
i // current position of i (Will move from 0 to 1)
See, the next element processed will be 5
, and not 2
. That is why your code is skipping an element.
You can solve this issue by iterating the array backwards, which will not modify the indices of remaining elements to be processed. And oh, you don't need nested for loop. Just single for loop will do the task.
Modify your loop as such:
for(int i = nElems; i > 0; i--) {
if (a[i] == a[i + 1]) {
delete(a[i]);
// nElems--; // Not needed here. (You're already doing this in delete())
}
}
Having said that all, consider using a Set
for this task. This is why Set
is there in Java API. It automatically removes the duplicate elements.