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.
  2. Print first k elements.

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&lt;int&gt; ());

// Printing first kth largest elements 

for (int i = 0; i &lt; k; i++)

	cout &lt;&lt; array[i] &lt;&lt; " ";

}

// 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);

}