
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
K-th Greatest Element in a Max-Heap in C++
In this tutorial, we are going to write a program that finds the k-th largest element from the max-heap.
We will use priority queue to solve the problem. Let's see the steps to complete the program.
- Initialise the max-heap with correct values.
- Create a priority queue and insert the root node of the max-heap.
- Write a loop that iterates k - 1 times.
- Pop the greatest element from the queue.
- Add the left and right nodes of the above node into the priority queue.
- The greatest element in priority queue is the k-th greatest element now.
- Return it.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; struct Heap { vector<int> elemets; int n; Heap(int i = 0): n(i) { elemets = vector<int>(n); } }; inline int leftIndex(int i) { return 2 * i + 1; } inline int rightIndex(int i) { return 2 * i + 2; } int findKthGreatestElement(Heap &heap, int k) { priority_queue<pair<int, int>> queue; queue.push(make_pair(heap.elemets[0], 0)); for (int i = 0; i < k - 1; ++i) { int node = queue.top().second; queue.pop(); int left = leftIndex(node), right = rightIndex(node); if (left < heap.n) { queue.push(make_pair(heap.elemets[left], left)); } if (right < heap.n) { queue.push(make_pair(heap.elemets[right], right)); } } return queue.top().first; } int main() { Heap heap(10); heap.elemets = vector<int>{ 44, 42, 35, 33, 31, 19, 27, 10, 26, 14 }; cout << findKthGreatestElement(heap, 4) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
33
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
- Related Articles
- Minimum element in a max heap in C++.
- Max Heap in Java
- Convert min Heap to max Heap in C++
- Is Max Heap in Python?
- Insertion into a Max Heap in Data Structure
- Deletion from a Max Heap in Data Structure
- k-th missing element in sorted array in C++
- K-th Element of Two Sorted Arrays in C++
- k-th missing element in an unsorted array in C++
- Convert BST to Max Heap in C++
- Program to check heap is forming max heap or not in Python
- Find k-th smallest element in given n ranges in C++
- Python program to find k'th smallest element in a 2D array
- C++ Program to Implement Max Heap
- Find k-th smallest element in BST (Order Statistics in BST) in C++

Advertisements