Kth Largest Element in Array

In this example, You learn about c++ program to find kth largest element in array.

Here you learn program to find kth largest element in C++, This problem you see on competitive programming websites like leetcode, hackerrank, etc.
 
kth largest element in an array

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
}

Output
Enter the value K
3
K'th largest element is 23
I hope you enjoy this example of kth largest element in array. If you have doubt leave it in the comment box below.
Happy Coding 😊

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form