In this example, You learn about c++ program to find kth largest element in array.
C++ Program to kth Largest Element in an Array
OutputI hope you enjoy this example of kth largest element in array. If you have doubt leave it in the comment box below.
Happy Coding 😊
Here you learn program to find kth largest element in C++, This problem you see on competitive programming websites like leetcode, hackerrank, etc.
Explanation
In this program, we simply use pre-built function to sort the array of n elements using sort function present in <algorithm> header file but it sort the elements in ascending order. So, To sort in descending order we use third arguments greater<int>()function it was sort in descending order, then we return K-1 element because our array indexing was start from "0".
C++ Program to kth Largest Element in an Array
#include <algorithm>
#include <iostream>
using namespace std;
int kthLargest(int arr[], int n, int k);
// Driver program to test above methods
int main()
{
int k, arr[] = { 32, 23, 15, 14, 43 };
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"Enter the value K"<<endl;
cin>>k;
cout<<"K'th largest element is " << kthLargest(arr, n, k);
return 0;
}
int kthLargest(int arr[], int n, int k)
{
sort(arr, arr + n, greater<int>()); //Sort the Array using pre-built sorting function and greater<int>() to sort in descending order.
return arr[k - 1]; // Return k'th Largest element in the sorted array
}
Enter the value K 3 K'th largest element is 23
Happy Coding 😊