mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Refactor MinHeap.
This commit is contained in:
parent
7dd977c3a4
commit
062f5a4929
@ -85,7 +85,7 @@ export default class MinHeap {
|
|||||||
|
|
||||||
while (
|
while (
|
||||||
MinHeap.hasParent(currentIndex) &&
|
MinHeap.hasParent(currentIndex) &&
|
||||||
this.parent(currentIndex) > this.heapContainer[currentIndex]
|
MinHeap.lessThen(this.heapContainer[currentIndex], this.parent(currentIndex))
|
||||||
) {
|
) {
|
||||||
this.swap(currentIndex, MinHeap.getParentIndex(currentIndex));
|
this.swap(currentIndex, MinHeap.getParentIndex(currentIndex));
|
||||||
currentIndex = MinHeap.getParentIndex(currentIndex);
|
currentIndex = MinHeap.getParentIndex(currentIndex);
|
||||||
@ -101,14 +101,14 @@ export default class MinHeap {
|
|||||||
while (this.hasLeftChild(currentIndex)) {
|
while (this.hasLeftChild(currentIndex)) {
|
||||||
if (
|
if (
|
||||||
this.hasRightChild(currentIndex) &&
|
this.hasRightChild(currentIndex) &&
|
||||||
this.leftChild(currentIndex) > this.rightChild(currentIndex)
|
MinHeap.lessThen(this.rightChild(currentIndex), this.leftChild(currentIndex))
|
||||||
) {
|
) {
|
||||||
nextIndex = MinHeap.getRightChildIndex(currentIndex);
|
nextIndex = MinHeap.getRightChildIndex(currentIndex);
|
||||||
} else {
|
} else {
|
||||||
nextIndex = MinHeap.getLeftChildIndex(currentIndex);
|
nextIndex = MinHeap.getLeftChildIndex(currentIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.heapContainer[currentIndex] < this.heapContainer[nextIndex]) {
|
if (MinHeap.lessThen(this.heapContainer[currentIndex], this.heapContainer[nextIndex])) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -120,4 +120,16 @@ export default class MinHeap {
|
|||||||
toString() {
|
toString() {
|
||||||
return this.heapContainer.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