Based on“Data Structures and Algorithm Analysis Edition 3.2 (C++ Version)” from C. A. Shaffer
Priority Queue & Heap
- A priority queue is an abstruct data type just like stack or queue, but additionally each element has a priority associated with it. In a priority queue, an element with high priority is served before an element with low priority.
- A heap is a data structure based on tree which satisfies the heap property. If the keys of parent nodes are always greater than or equal to those of the children, it’s called a max heap; If the keys of parent nodes are always smaller than or equal to those of the children, it’s called a min heap. The operations commonly performed with a heap are:
- create-heap: create an empty heap
- heapify: create a heap out of given array of elements
- find-max or find-min: find the maximum item of a max-heap or a minimum item of a min-heap.
- delete-max or delete-min: removing the root node of a max- or min-heap, respectively
- increase-key or decrease-key: updating a key within a max- or min-heap, respectively
- insert: adding a new key to the heap
- merge: joining two heaps to form a valid new heap containing all the elements of both.
Binary Heap
Defination
A binary heap is a heap data structure created using a complete binary tree which satisfies the heap property.
There are max binary heaps and min binary heaps. we just talk about min ones, and max ones are just the same.
Operation
Sift-up & Sift-down
Sift-up and sift-down are the fundamental operation of binary heaps, which is used by building, inserting, deleting, etc.
For a min binary heap, the sift-down operation is just compare the node with it’s children. If it’s greater than one of it’s children, then swap these two nodes; if it’s key is greater than both of it’s children, then swap it with the smaller children. Do this until the node becomes a leaf node or it’s smaller than both of it’s children.
The sift-up operation is just compare the node with it’s parent. If the node is smaller than it’s parent, then swap it with it’s parent. Do this until the node becomes the root node or it’s greater than it’s parent.
Insert
To insert a node into the binary heap, first add it at the end of the binary heap. Then do sift-up to the node until the node becomes the root node or it’s greater than it’s parent. It’s cost is about O(logn) .
Delete
To delete a node from the binary heap, first swap it with the last node in the binary tree, then delete the last node, then do sift-up or sift-down to the new node at the original position. It’s cost is about O(logn)
Build
To build a binary tree with a set of given elements, first build a complete binary tree without priority, the from the last internal node to the root node, do sift-down one by one. It’s cost is about O(n) .