heap
What is a heap?
A heap is a special kind of complete binary tree. The meaning of a complete binary tree is that each layer of nodes is completely filled, except for the last layer, only a few nodes are allowed to be missing on the far right. Arrays are usually used to represent heaps in JavaScript (in breadth-first traversal order).
max heap
min heap
characteristic
- All nodes are greater than or equal to its children (max heap)
- Or all nodes are less than or equal to its child nodes (min heap)
- The position of the left child node is 2_index + 1
- The position of the right child node is 2_index + 2 (that is, based on the left child node + 1)
- The position of the parent node is (index - 1) / 2
advantage
- Efficiently and quickly find the maximum and minimum values of the heap, the time complexity is O (1)
- Find the Kth largest and smallest element
common operation
insert
- inserts a value at the bottom of the heap, i.e. the tail of the data
- Then move up and exchange this value with its parent node until the parent node is less than or equal to the inserted value
- The time complexity of inserting an element in a heap of size k is O(logK)
delete heap top
- Replace the top of the heap with the elements at the end of the array (directly deleting the top of the heap will destroy the structure)
- Then move down and exchange the new top of the heap with its child nodes until the child node is greater than or equal to the new top of the heap
- The time complexity of deleting the top of the heap in a heap of size k is O(logK)
get top of heap
- Returns the 0th item of the array
get heap size
- Returns the length of the array
base case
Realize the minimum heap through Class
class MinHeap {
constructor() {
this.heap = []
}
top() {
return this.heap[0]
}
size() {
return this.heap.length
}
getChildLeftIndex(i) {
return i * 2 + 1
}
getChildRightIndex(i) {
return i * 2 + 2
}
getParentIndex(i) {
return (i - 1) >> 1
}
swap(index1, index2) {
const temp = this.heap[index1]
this.heap[index1] = this.heap[index2]
this.heap[index2] = temp
}
shiftUp(index) {
if (index === 0) return
const parentIndex = this.getParentIndex(index)
if (this.heap[parentIndex] > this.heap[index]) {
this.swap(parentIndex, index)
this.shiftUp(parentIndex)
}
}
shiftDown(index) {
const leftChildIndex = this.getChildLeftIndex(index)
const rightChildIndex = this.getChildRightIndex(index)
if (this.heap[leftChildIndex] < this.heap[index]) {
this.swap(leftChildIndex, index)
this.shiftDown(leftChildIndex)
}
if (this.heap[rightChildIndex] < this.heap[index]) {
this.swap(rightChildIndex, index)
this.shiftDown(rightChildIndex)
}
}
insert(value) {
this.heap.push(value)
this.shiftUp(this.heap.length - 1)
}
pop() {
this.heap[0] = this.heap.pop()
this.shiftDown(0)
}
}
const h = new MinHeap()
h.insert(3)
h.insert(2)
h.insert(1)
h.pop()
Original Link: Vegetable Garden Front End