File tree Expand file tree Collapse file tree 1 file changed +10
-10
lines changed
src/data-structures/heaps Expand file tree Collapse file tree 1 file changed +10
-10
lines changed Original file line number Diff line number Diff line change @@ -33,11 +33,11 @@ class Heap {
3333 * Retrieves and removes the head of this heap, or returns null if this heap is empty.
3434 * @runtime O(log n)
3535 */
36- remove ( ) {
36+ remove ( index = 0 ) {
3737 if ( ! this . size ( ) ) return null ;
38- this . swap ( 0 , this . size ( ) - 1 ) ;
39- const value = this . array . pop ( ) ;
40- this . bubbleDown ( ) ;
38+ this . swap ( index , this . size ( ) - 1 ) ; // swap with last
39+ const value = this . array . pop ( ) ; // remove element
40+ this . bubbleDown ( index ) ;
4141 return value ;
4242 }
4343
@@ -66,17 +66,17 @@ class Heap {
6666 * After removal, moves element downwards on the heap, if it's out of order
6767 * @runtime O(log n)
6868 */
69- bubbleDown ( ) {
70- let index = 0 ;
69+ bubbleDown ( index = 0 ) {
70+ let curr = index ;
7171 const left = ( i ) => 2 * i + 1 ;
7272 const right = ( i ) => 2 * i + 2 ;
7373 const getTopChild = ( i ) => ( right ( i ) < this . size ( )
7474 && this . comparator ( left ( i ) , right ( i ) ) > 0 ? right ( i ) : left ( i ) ) ;
7575
76- while ( left ( index ) < this . size ( ) && this . comparator ( index , getTopChild ( index ) ) > 0 ) {
77- const next = getTopChild ( index ) ;
78- this . swap ( index , next ) ;
79- index = next ;
76+ while ( left ( curr ) < this . size ( ) && this . comparator ( curr , getTopChild ( curr ) ) > 0 ) {
77+ const next = getTopChild ( curr ) ;
78+ this . swap ( curr , next ) ;
79+ curr = next ;
8080 }
8181 }
8282
You can’t perform that action at this time.
0 commit comments