Date:

Share:

Kth Largest Element in Array

Related Articles

In this example, you learn about the c ++ program to find the k largest component in an array.


Here you learn Program to find the k largest component in C ++, this problem you see in competitive programming sites like leetcode, hackerrank etc.

explanation

In this program, we simply use a pre-built function to sort the array of n elements using an existing sort function in <אלגוריתם> Header file but it sorts the elements in ascending order. Therefore, to sort in descending order we use third arguments bigger() This function was sorting in descending order, then we return element K-1 because our array index started from “0”.


#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

Productivity

Enter the value K
3
K'th largest element is 23

I hope you enjoy this example of The k largest element in the array. If in doubt leave it in the comments box below.
Happy Coding 😊

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles