Added support for isValid heap
This commit is contained in:
parent
ac8a04c154
commit
59cfea1f4b
1 changed files with 35 additions and 0 deletions
|
@ -128,6 +128,41 @@ public class BinaryHeap<E extends Comparable<E>> implements PriorityQueue<E> {
|
|||
return this.currentSize;
|
||||
}
|
||||
|
||||
public boolean isValid() {
|
||||
|
||||
if(this.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return isValid(0);
|
||||
}
|
||||
|
||||
private boolean isValid(int indexStart) {
|
||||
//on doit vérifier que l'index est plus petit que ses deux parents
|
||||
|
||||
int ileft = indexLeft(indexStart);
|
||||
int iright = ileft + 1;
|
||||
boolean hasRight = iright < this.currentSize;
|
||||
boolean hasLeft = ileft < this.currentSize;
|
||||
|
||||
|
||||
if(hasRight) {
|
||||
//si on a un point à droite on vérifie que le point est valide, puis que tous les points en dessous à droite le sont.
|
||||
if(this.array.get(indexStart).compareTo(this.array.get(iright)) > 0)return false;
|
||||
if(!isValid(iright))return false;
|
||||
}
|
||||
if(hasLeft) {
|
||||
//si on a un point à gauche on vérifie que le point est valide, puis que tous les points en dessous à gauche le sont aussi.
|
||||
if(this.array.get(indexStart).compareTo(this.array.get(ileft)) > 0)return false;
|
||||
if(!isValid(ileft))return false;
|
||||
}
|
||||
|
||||
//ici, on a vérifié une branche ou les deux ou zéro, et on a pas fail donc c'est tout bon !
|
||||
return true;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(E x) {
|
||||
int index = this.currentSize++;
|
||||
|
|
Loading…
Reference in a new issue