Skip to content

Instantly share code, notes, and snippets.

@Ram-1234
Last active May 22, 2021 01:54
Show Gist options
  • Save Ram-1234/9bc157bac61862951da7b6c3f383301a to your computer and use it in GitHub Desktop.
Save Ram-1234/9bc157bac61862951da7b6c3f383301a to your computer and use it in GitHub Desktop.
Kth largest array element without array sort method, using min heap
example:-
input:
array size=5
kth =3
arr[]={9 12 2 15 2}
output:
9
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
int k=sc.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++){
arr[i]=sc.nextInt();
}
PriorityQueue<Integer> minhip=new PriorityQueue<>();
for(int i:arr){
if(!minhip.contains(i)){
minhip.add(i);
}
if(minhip.size()>k){
minhip.remove();
}
}
System.out.println(minhip.remove());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment