What is the priority Queue?
Basically, Priority queues are abstract data types and are quite similar to queues, however, in the priority queue, there is some priority for every element. The priority or every element states the order of the particular element i.e. in which order an element is added or removed from the priority queue. Therefore, All the elements in the priority queue are arranged in either ascending or descending order.
Operations of Priority queue:
- Get Priority element (smallest or largest)
- Insert an element
- Remove an element
- Decrease the key
What is Binary Heap?
A Binary Heap is a complete binary tree i.e. All levels of the tree are completely filled except the last level. Binary heaps are either min heap or max heap. In the min-heap, the value at the root node must be smaller than its child or we can say minimum value among the tree. In the max heap, the value at the root node must be the greatest node among the whole tree.
A binary heap follows a heap ordering property.
A binary heaps support the above priority queue operation with effective time complexity:
- Get Priority element (smallest or largest) in O(1)
- Insert an element in O(log n)
- Remove an element in O(log n)
- Decrease the key in O(log n)
So why are Binary heaps preferred:
- As we know binary heaps are implemented using arrays, due to which operations are more efficient.
- We can build a binary heap with a time complexity of O(N).
- Also, Binary heaps don’t have any extra space.
- Binary heaps are easy to implement.
- And also there are some variations of binary heaps like in Fibonacci heaps that can support insertion and decrease key operations in O(1) time.
This article tried to discuss the Implementation of heap sort in C++. Hope this blog helps you understand the concept. To practice more problems you can check out MYCODE | Competitive Programming.