- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Kth Largest Element in an Array
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
Advertisements