What’s the best algorithm of these 2 (in Java) to delete certain values in a list?
1: using an arraylist
2: using a linkedlist
for (int i = arraylist.size()-1; i >= 0; i--) {
if(arraylist.get(i).getValue() < 20)
list.remove(i);
}
or
for (int i = linkedlist.size()-1; i >= 0; i--) {
if(linkedlist.get(i).getValue() < 20)
list.remove(i);
}
Also, what’s the complexity of these 2 algorithms? (if in for loop)?
I think it’s O(n), but I am not sure…
LinkedListYou should never, ever iterate over a linked list by indexing into it. Indexing into a linked list is an
O(n)operation. Here’s a break-down:nsteps =>O(n)operation.O(n)operation.O(n)operation.In each step of the iteration from 1. above, you perform an O(n) operation two times. This is
2n * O(n)which is equivalent toO(n^2).To remove from a linked list in
O(n)time, you need to use its internal iterator mechanism to iterate over it, and toiterator.remove()items from it if they match your criteria.ArarayListFor the array-based list, the problem is that the remove operation is an
O(n)operation: the items on the right of the removed element need to be moved over to the left. Going from the right-hand side doesn’t solve anything because stored values still need to be moved to the left if you remove something on the far left-hand side of the array. Breakdown:nsteps =>O(n)operation.O(1)operation.O(n)operation.Which gives you
O(n^2)performance.You cannot remove elements from an
ArrayListwithout having this sort of performance due to the remove operation beingO(n)(unless the array is sorted and copying a portion of array is considered anO(n)operation).