2525
2626namespace doganoo \PHPAlgorithms \Datastructure \Graph \Tree \Heap ;
2727
28+ use doganoo \PHPAlgorithms \Common \Exception \IndexOutOfBoundsException ;
2829use doganoo \PHPAlgorithms \Common \Interfaces \IHeap ;
2930use doganoo \PHPAlgorithms \Common \Util \Comparator ;
3031
@@ -65,6 +66,7 @@ public function clear(): bool {
6566
6667 /**
6768 * @param int $element
69+ * @throws IndexOutOfBoundsException
6870 */
6971 public function insert (int $ element ): void {
7072 $ length = $ this ->length ();
@@ -75,8 +77,15 @@ public function insert(int $element): void {
7577 $ current = $ this ->heap [$ currentPosition ];
7678 $ parent = $ this ->heap [$ parentPosition ];
7779
80+ //this could be implemented in recursive way as well!
7881 while (Comparator::greaterThan ($ current , $ parent )) {
7982 $ this ->swap ($ currentPosition , $ parentPosition );
83+ //since we have swapped the positions, we need
84+ //to redefine our current position and parent position
85+ //and 'bubble up':
86+ //the current position is the parent position and the
87+ //parent position is the parent position of the current position
88+ //(i know, it is confusing :-))
8089 $ currentPosition = $ this ->getParentPosition ($ currentPosition );
8190 $ parentPosition = $ this ->getParentPosition ($ currentPosition );
8291 $ current = $ this ->heap [$ currentPosition ];
@@ -120,9 +129,11 @@ public function length(): int {
120129 *
121130 * @param int $pos
122131 * @return int
132+ * @throws IndexOutOfBoundsException
123133 */
124134 public function getParentPosition (int $ pos ): int {
125- return $ pos === 0 ? 0 : $ pos / 2 ;
135+ if ($ pos < 0 ) throw new IndexOutOfBoundsException ("$ pos < 0 " );
136+ return $ pos === 0 ? 0 : \intval ($ pos / 2 );
126137 }
127138
128139 /**
0 commit comments