RUN


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

}

Report Error/ Suggestion

Related Posts:

[yuzo_views]



Interview Questions



CopyRight © 2020

CopyRight © 2020