- 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
- Related Articles
- Kth Largest Element in an Array in Python
- Kth Largest Element in a Stream in Python
- C++ Program to Find kth Largest Element in a Sequence
- Swap kth element of array - JavaScript
- Python Program to find largest element in an array
- kth smallest/largest in a small range unsorted array in C++
- Program to find largest element in an array in C++
- Python Program to find the largest element in an array
- Golang Program to Find the Largest Element in an Array
- C++ Program to Find Largest Element of an Array
- C# Program to find the largest element from an array
- Detecting the largest element in an array of Numbers (nested) in JavaScript
- Kth odd number in an array in C++
- Find maximum sum taking every Kth element in the array in C++
- K’th Smallest/Largest Element in Unsorted Array in C++

Advertisements