mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
Refactor MinHeap.
This commit is contained in:
parent
7dd977c3a4
commit
062f5a4929
@ -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;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user