ajout: Implémentation de BinaryHeap#remove(E x)
This commit is contained in:
parent
63fb8fa6af
commit
a35c883c44
1 changed files with 31 additions and 1 deletions
|
|
@ -1,6 +1,9 @@
|
||||||
package org.insa.graphs.algorithm.utils;
|
package org.insa.graphs.algorithm.utils;
|
||||||
|
|
||||||
|
import java.util.ArrayDeque;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Queue;
|
||||||
|
import java.util.Stack;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implements a binary heap containing elements of type E. Note that all comparisons are
|
* Implements a binary heap containing elements of type E. Note that all comparisons are
|
||||||
|
|
@ -134,7 +137,34 @@ 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 {
|
||||||
// TODO:
|
if (this.isEmpty()) throw new ElementNotFoundException(x);
|
||||||
|
|
||||||
|
Stack<Integer> stack = new Stack<>();
|
||||||
|
stack.add(0);
|
||||||
|
while (!stack.isEmpty()) {
|
||||||
|
int i = stack.pop();
|
||||||
|
System.out.println("i=" + i);
|
||||||
|
E current = this.array.get(i);
|
||||||
|
int comp = current.compareTo(x);
|
||||||
|
if (comp == 0) {
|
||||||
|
// on a trouvé notre élément
|
||||||
|
this.currentSize--;
|
||||||
|
if (this.currentSize > 0) {
|
||||||
|
E lastItem = this.array.get(this.currentSize);
|
||||||
|
this.arraySet(i, lastItem);
|
||||||
|
this.percolateDown(i);
|
||||||
|
this.percolateUp(i);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
int indLeft = indexLeft(i);
|
||||||
|
if (indLeft < this.currentSize) stack.push(indLeft);
|
||||||
|
int indRight = indLeft+1;
|
||||||
|
if (indRight < this.currentSize) stack.push(indRight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ElementNotFoundException(x);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue