package
0.0.0-20250206101203-bd6683890685
Repository: https://github.com/dockerian/go-coding.git
Documentation: pkg.go.dev
# README
Binary Heap
Data Structure
A binary heap is a heap data structure created using a binary tree.
Binary heap has two rules:
- Shape property: Binary Heap has to be complete binary tree at all levels except the last level.
- Heap property: All nodes are either greater than equal to (Max-Heap) or less than equal to (Min-Heap) to each of its child nodes.
Implementation:
- Use array to store the data.
- Start storing from index 1, not 0.
- For any given node at position
[i]
:- its Left Child is at
[2*i]
if available. - its Right Child is at
[2*i+1]
if available. - its Parent Node is at
[i/2]
if available.
- its Left Child is at
Heap Operations
Insert
- Add the element at the bottom leaf of the Heap.
- Perform the Bubble-Up operation: ~ O(log n)
- Bubble-Up a.k.a up-heap, percolate-up, sift-up, trickle-up, heapify-up, or cascade-up
- If inserted element is smaller than its parent node in case of Min-Heap OR greater than its parent node in case of Max-Heap, swap the element with its parent.
- Keep repeating the above step, if node reaches its correct position, STOP.
Extract-Min OR Extract-Max Operation
- Take out the element from the root.( it will be minimum in case of Min-Heap and maximum in case of Max-Heap).
- Take out the last element from the last level from the heap and replace the root with the element.
- Perform Sink-Down
Delete
- Find the index for the element to be deleted.
- Take out the last element from the last level from the heap and replace the index with this element.
- Perform Sink-Down operation: ~ O(log n)
- If replaced element is greater than any of its child node in case of Min-Heap OR smaller than any if its child node in case of Max-Heap, swap the element with its smallest child (Min-Heap) or with its greatest child (Max-Heap).
- Keep repeating the above step, if node reaches its correct position, STOP.
See http://algorithms.tutorialhorizon.com/binary-min-max-heap/
# Type aliases
Heap is a list of *Item.
MinIntHeap is a min-heap of integers.
PriorityQueue is a list of *Item.