Skip to content

Commit e96e33e

Browse files
Merge pull request #271 from Gourav-s12/master
Create kthLargestElement.java
2 parents 514450c + 4e0ac6c commit e96e33e

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*Find k’th largest element in an array
2+
Input:
3+
4+
arr = [7, 4, 6, 3, 9, 1]
5+
k = 2
6+
7+
Output:
8+
9+
The 2nd largest array element is 7
10+
*/
11+
12+
import java.util.*;
13+
class kthLargestElement
14+
{
15+
public static void main (String args[])
16+
{
17+
int n,k;
18+
// using max heap to solve and find kth largest element
19+
Scanner s= new Scanner(System.in);
20+
PriorityQueue < Integer > queue =
21+
new PriorityQueue < Integer > (Comparator.reverseOrder ());
22+
//using PriorityQueue as a heap data structure
23+
System.out.println("enter the array length:");
24+
n=s.nextInt(); //taking array length as a input
25+
System.out.println("enter the element:");
26+
for(int i=0;i<n;i++)
27+
queue.add (s.nextInt()); //adding elements in heap (it does in-build sort)
28+
System.out.println("enter the value of k:");
29+
k=s.nextInt(); //taking the value of k
30+
if(k>n){
31+
System.out.println("the value of k should not be more than array length!! error");
32+
return; // k must be less than n
33+
}
34+
while(k>1){
35+
queue.poll (); //removing (k-1) elements from max heap
36+
k--; //so that next max element is the kth largest
37+
}
38+
System.out.println ("the kth largest element is:" + queue.peek ());//to get the max element in max heap (root element)
39+
}
40+
}

0 commit comments

Comments
 (0)