Get rid of array.indexOf(x) in the remove() function
This commit is contained in:
parent
53e9facf47
commit
8f74486264
1 changed files with 12 additions and 2 deletions
|
@ -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);
|
||||||
|
|
Loading…
Reference in a new issue