Implémentation remove avec indexOf

This commit is contained in:
Arnaud Vergnet 2020-03-25 16:23:31 +01:00
parent 51c027f3b7
commit 558a665ec0

View file

@ -4,7 +4,7 @@ import java.util.ArrayList;
/**
* Implements a binary heap containing elements of type E.
*
* <p>
* Note that all comparisons are based on the compareTo method, hence E must
* implement Comparable
*
@ -46,8 +46,7 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
private void arraySet(int index, E value) {
if (index == this.array.size()) {
this.array.add(value);
}
else {
} else {
this.array.set(index, value);
}
}
@ -76,7 +75,7 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
for (; index > 0
&& x.compareTo(this.array.get(indexParent(index))) < 0; index = indexParent(
index)) {
index)) {
E moving_val = this.array.get(indexParent(index));
this.arraySet(index, moving_val);
}
@ -106,8 +105,7 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
this.arraySet(ileft, current);
this.percolateDown(ileft);
}
}
else {
} else {
// Right is smaller
if (right.compareTo(current) < 0) {
this.arraySet(index, right);
@ -137,7 +135,24 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
@Override
public void remove(E x) throws ElementNotFoundException {
// TODO:
int index = this.array.indexOf(x);
System.out.println(x);
System.out.println(index);
if (isEmpty() || index == -1 || index >= this.currentSize)
throw new ElementNotFoundException(x);
else if (index == 0)
deleteMin();
else if (index == this.currentSize-1)
this.currentSize--;
else {
System.out.println(this.toStringTree());
E lastItem = this.array.get(--this.currentSize);
System.out.println(lastItem);
this.arraySet(index, lastItem);
this.percolateDown(index);
this.percolateUp(index);
System.out.println(this.toStringTree());
}
}
@Override
@ -170,7 +185,6 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
*
* @param maxElement Maximum number of elements to display. or {@code -1} to
* display all the elements.
*
* @return a string containing a sorted view this binary heap.
*/
public String toStringSorted(int maxElement) {
@ -190,7 +204,6 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
* Creates a multi-lines string representing a tree view of this binary heap.
*
* @param maxDepth Maximum depth of the tree to display.
*
* @return a string containing a tree view of this binary heap.
*/
public String toStringTree(int maxDepth) {