Skip to content

Instantly share code, notes, and snippets.

@thmain
Created May 27, 2018 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/e1879523f97b631f877a8ef041666527 to your computer and use it in GitHub Desktop.
Save thmain/e1879523f97b631f877a8ef041666527 to your computer and use it in GitHub Desktop.
import java.util.PriorityQueue;
public class KthSmallestElementInArray {
public static int find(int [] A, int k){
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int i=0;i<A.length;i++){
pq.offer(A[i]);
}
int n = -1;
while(k>0){
n = pq.poll();
k--;
}
return n;
}
public static void main(String[] args) {
int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 };
int k = 4;
System.out.println("4th smallest element:" + find(A,4));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment