Get rid of array.indexOf(x) in the remove() function

This commit is contained in:
Yohan Simard 2020-04-02 23:20:33 +02:00
parent 53e9facf47
commit 8f74486264

View file

@ -137,8 +137,18 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
@Override @Override
public void remove(E x) throws ElementNotFoundException { public void remove(E x) throws ElementNotFoundException {
int index = array.indexOf(x); int index = 0;
if (index == -1 || index >= currentSize) throw new ElementNotFoundException(x); // We avoid array.indexOf(x) because we don't need to search
// through the whole list, we can stop at indexSize.
boolean found = false;
while(!found && index < currentSize) {
if (array.get(index) == x)
found =true;
else
index++;
}
if (!found) throw new ElementNotFoundException(x);
arraySet(index, array.get(--currentSize)); arraySet(index, array.get(--currentSize));
percolateUp(index); percolateUp(index);
percolateDown(index); percolateDown(index);