

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Find kth Largest Element in a Sequence
In this program, we need to extract the Kth largest element from a sequence. the time complexity of this technique can be improved by approaching the problem using max-heap. The time complexity of this program is O(n + k*log(n)).
Algorithm
Begin Send the max of the heap to the end of the sequence. Heapify the remaining sequence. Repeat the process for ‘k’ times. Print the final state of the array. Print the max from the heap extracted from kth iteration as a result. End.
Example Code
#include <iostream> using namespace std; void MaxHeapify(int a[], int i, int n) { int j, t; t = a[i]; j = 2*i; while (j <= n) { if (j < n && a[j+1] > a[j]) j = j+1; if (t > a[j]) break; else if (t <= a[j]) { a[j/2] = a[j]; j = 2*j; } } a[j/2] = t; return; } void Build_MaxHeapify(int a[], int n) { int i; for(i = n/2; i >= 1; i--) MaxHeapify(a, i, n); } int main() { int n, i, temp, k; cout<<"\nEnter the number of data element to be sorted: "; cin>>n; n++; int arr[n]; for(i = 1; i < n; i++) { cout<<"Enter element "<<i<<": "; cin>>arr[i]; } cout<<"\nEnter the k value: "; cin>>k; Build_MaxHeapify(arr, n-1); for(i = n-1; i >= n-k; i--) { temp = arr[i]; arr[i] = arr[1]; arr[1] = temp; MaxHeapify(arr, 1, i - 1); } cout<<"\nAfter max-heapify the given array "<<k<<" times the array state is: "; for(i = 1; i < n; i++) cout<<"->"<<arr[i]; cout<<"\n\nThe "<<k<<"th largest element is: "<<arr[n-k]; return 0; }
Output
Enter the number of data element to be sorted: 5 Enter element 1: 20 Enter element 2: 10 Enter element 3: 30 Enter element 4: 70 Enter element 5: 60 Enter the k value: 2 After max-heapify the given array 2 times the array state is: ->30->20->10->60->70 The 2th largest element is: 60
- Related Questions & Answers
- Kth Largest Element in an Array
- Kth Largest Element in a Stream in Python
- Kth Largest Element in an Array in Python
- Program to find largest kth index value of one list in Python
- Program to find kth smallest element in linear time in Python
- Python Program to find largest element in an array
- Program to find kth lexicographic sequence from 1 to n of size k Python
- Python – Find Kth Even Element
- Program to find the kth smallest element in a Binary Search Tree in Python
- Program to find largest element in an array in C++
- C++ Program to Find Largest Element of an Array
- Python Program to find the largest element in an array
- Python Program to Find the Largest Element in a Doubly Linked List
- C# Program to find the largest element from an array
- Program to construct the lexicographically largest valid sequence in Python
Advertisements