Kth Largest Element in an Array

Misc AlgorithmsData StructureAlgorithms

From a set of data, this algorithm will find the largest element to kth largest element of the array.

This problem can be solved easily by sorting the array. We can sort them either in ascending order or in descending order. Solving it in descending order, we can get first k elements to find our result.

Input and Output

Input:
The elements of an array: {1, 23, 12, 9, 30, 2, 50, 63, 87, 12, 45, 21}, K = 4
Output:
4 largest elements are 87 63 50 45

Algorithm

kthLargestElement(array, n, k)

Input: The array, number of elements in the array, place k.

Output: Display largest element to kth largest elements of the array.

Begin
   sort the array in descending order
   for i := 0 to k-1, do
      display array[i]
   done
End

Example

#include<iostream>
#include<algorithm>
using namespace std;

bool compare(int a, int b) {
   return a>b;
}

void kthLargestElement(int array[], int n, int k) {
   sort(array, array+n, compare);

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

int main() {
   int array[] = {1, 23, 12, 9, 30, 2, 50, 63, 87, 12, 45, 21};
   int n = 12;
   int k = 4;
   kthLargestElement(array, n, k);
}

Output

87 63 50 45
raja
Published on 12-Jul-2018 09:25:32
Advertisements