满二叉树
完全二叉树
class MinHeap {
constructor(compareFn = defaultCompare) {
this.compareFn = compareFn;
this.heap = [];
}
insert(value){} //插入
peek(){} //访问根结点
poll(){} //移除根结点,并返回根节点
}
const Compare = {
LESS_THAN: -1,
BIGGER_THAN: 1,
EQUALS: 0
}
function defaultCompare(a, b) {
if (a === b) {
return Compare.EQUALS;
}
return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN;
}
getLeftIndex(index) {
return (2 * index) + 1;
}
getRightIndex(index) {
return (2 * index) + 2;
}
getParentIndex(index) {
if (index === 0) {
return undefined;
}
return Math.floor((index - 1) / 2);
}
size() {
return this.heap.length;
}
isEmpty() {
return this.size() <= 0;
}
clear() {
this.heap = [];
}
swap(a, b) {
/* const temp = this.heap[a];
this.heap[a] = this.heap[b];
this.heap[b] = temp; */
[this.heap[a], this.heap[b]] = [this.heap[b], this.heap[a]];
}
insert(value) {
if (value != null) {
const index = this.heap.length;
this.heap.push(value);
this.siftUp(index); //上移堆化
return true;
}
return false;
}
siftUp(index) {
let parent = this.getParentIndex(index);
while (
index > 0
&& this.compareFn(this.heap[parent],
this.heap[index]) === Compare.BIGGER_THAN
) {
swap(parent, index);
index = parent;
parent = this.getParentIndex(index);
}
}
const heap = new MinHeap();
heap.insert(2);
heap.insert(3);
heap.insert(4);
heap.insert(5);
heap.insert(1);
peek() {
return this.isEmpty() ? undefined : this.heap[0];
}
poll() {
if (this.isEmpty()) {
return undefined;
}
if (this.size() === 1) {
return this.heap.shift();
}
const removedValue = this.heap[0];
this.heap[0] = this.heap.pop();
this.siftDown(0);//下移堆化
return removedValue;
}
siftDown(index) {
let element = index;
const left = this.getLeftIndex(index);
const right = this.getRightIndex(index);
const size = this.size();
if (
left < size
&& this.compareFn(this.heap[element],
this.heap[left]) === Compare.BIGGER_THAN
) {
element = left;
}
if (
right < size
&& this.compareFn(this.heap[element],
this.heap[right]) === Compare.BIGGER_THAN
) {
element = right;
}
if (index !== element) {
swap(index, element);
this.siftDown(element);
}
}
class MaxHeap extends MinHeap {
constructor(compareFn = defaultCompare) {
super(compareFn);
this.compareFn = reverseCompare(compareFn);
}
}
function reverseCompare(compareFn) {
return (a, b) => compareFn(b, a);
}
const maxHeap = new MaxHeap();
maxHeap.insert(2);
maxHeap.insert(3)
maxHeap.insert(4);
maxHeap.insert(5);
maxHeap.insert(1);
console.log('Heap size: ', maxHeap.size()); // 5
console.log('Heap min value: ', maxHeap.peek()); // 5
function sort(originalArray) {
const sortedArray = [];
const minHeap = new MinHeap();
// Insert all array elements to the heap.
originalArray.forEach((element) => {
minHeap.insert(element);
});
while (!minHeap.isEmpty()) {
const nextMinElement = minHeap.poll();
sortedArray.push(nextMinElement);
}
return sortedArray;
}
请用堆排序算法将数组[9, 8, 7, 6, 5, 4, 3, 2, 1]按升序排序。