Program to find k largest elements in a given array of integers in C++

Given – array of integers and we have to print k number of largest elements from the array.

Example:

Given array is [12, 20, 14, 26, 30, 1, 70, 56] 

We have to find largest 4 elements i.e., k = 4 

Therefore our program should print 70, 56, 30 and 26.

Algorithm:

  1. Sort the given array in ascending order using the sort function.
  2. Print the first k elements of the sorted array using a loop.

Code:

#include <bits/stdc++.h>
using namespace std;

void kLarge(int array[], int size, int k)
{
    // Sorting given array in reverse order
    sort(array, array + size, greater<int> ());

    // Printing first kth largest elements
    for (int i = 0; i < k; i++)
        cout << array[i] << " ";
}

// driver program
int main()
{
    int array[] = { 12, 20, 14, 26, 30, 1, 70, 56 };
    int size = sizeof(array) / sizeof(array[0]);
    int k = 4;
    kLarge(array, size, k);
    return 0;
}

Output

70 56 30 26
Program to find k largest elements in a given array of integers in C++