Skip to content

Commit

Permalink
Refactor MinHeap.
Browse files Browse the repository at this point in the history
  • Loading branch information
trekhleb committed Apr 3, 2018
1 parent 7dd977c commit 062f5a4
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/data-structures/heap/MinHeap.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
}

Expand All @@ -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;
}
}

0 comments on commit 062f5a4

Please sign in to comment.