MCPcopy Index your code
hub / github.com/trekhleb/javascript-algorithms / heapifyDown

Method heapifyDown

src/data-structures/heap/Heap.js:241–268  ·  view source on GitHub ↗

* @param {number} [customStartIndex]

(customStartIndex = 0)

Source from the content-addressed store, hash-verified

239 * @param {number} [customStartIndex]
240 */
241 heapifyDown(customStartIndex = 0) {
242 // Compare the parent element to its children and swap parent with the appropriate
243 // child (smallest child for MinHeap, largest child for MaxHeap).
244 // Do the same for next children after swap.
245 let currentIndex = customStartIndex;
246 let nextIndex = null;
247
248 while (this.hasLeftChild(currentIndex)) {
249 if (
250 this.hasRightChild(currentIndex)
251 && this.pairIsInCorrectOrder(this.rightChild(currentIndex), this.leftChild(currentIndex))
252 ) {
253 nextIndex = this.getRightChildIndex(currentIndex);
254 } else {
255 nextIndex = this.getLeftChildIndex(currentIndex);
256 }
257
258 if (this.pairIsInCorrectOrder(
259 this.heapContainer[currentIndex],
260 this.heapContainer[nextIndex],
261 )) {
262 break;
263 }
264
265 this.swap(currentIndex, nextIndex);
266 currentIndex = nextIndex;
267 }
268 }
269
270 /**
271 * Checks if pair of heap elements is in correct order.

Callers 2

pollMethod · 0.95
removeMethod · 0.95

Calls 8

hasLeftChildMethod · 0.95
hasRightChildMethod · 0.95
pairIsInCorrectOrderMethod · 0.95
rightChildMethod · 0.95
leftChildMethod · 0.95
getRightChildIndexMethod · 0.95
getLeftChildIndexMethod · 0.95
swapMethod · 0.95

Tested by

no test coverage detected