From 062f5a49295d9b3d025930b5853fabc288d7f383 Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Tue, 3 Apr 2018 18:04:44 +0300 Subject: [PATCH] Refactor MinHeap. --- src/data-structures/heap/MinHeap.js | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/data-structures/heap/MinHeap.js b/src/data-structures/heap/MinHeap.js index 05d7f38a..d8e92c77 100644 --- a/src/data-structures/heap/MinHeap.js +++ b/src/data-structures/heap/MinHeap.js @@ -85,7 +85,7 @@ export default class MinHeap { while ( MinHeap.hasParent(currentIndex) && - this.parent(currentIndex) > this.heapContainer[currentIndex] + MinHeap.lessThen(this.heapContainer[currentIndex], this.parent(currentIndex)) ) { this.swap(currentIndex, MinHeap.getParentIndex(currentIndex)); currentIndex = MinHeap.getParentIndex(currentIndex); @@ -101,14 +101,14 @@ export default class MinHeap { while (this.hasLeftChild(currentIndex)) { if ( this.hasRightChild(currentIndex) && - this.leftChild(currentIndex) > this.rightChild(currentIndex) + MinHeap.lessThen(this.rightChild(currentIndex), this.leftChild(currentIndex)) ) { nextIndex = MinHeap.getRightChildIndex(currentIndex); } else { nextIndex = MinHeap.getLeftChildIndex(currentIndex); } - if (this.heapContainer[currentIndex] < this.heapContainer[nextIndex]) { + if (MinHeap.lessThen(this.heapContainer[currentIndex], this.heapContainer[nextIndex])) { break; } @@ -120,4 +120,16 @@ export default class MinHeap { toString() { return this.heapContainer.toString(); } + + static compare(a, b) { + if (a === b) { + return 0; + } + + return a < b ? -1 : 1; + } + + static lessThen(a, b) { + return MinHeap.compare(a, b) === -1; + } }