|
| 1 | +package LoveBabbarDSA; |
| 2 | + |
| 3 | +// { Driver Code Starts |
| 4 | +//Initial Template for Java |
| 5 | + |
| 6 | +/*package whatever //do not write package name here */ |
| 7 | + |
| 8 | +import java.io.*; |
| 9 | +import java.util.*; |
| 10 | +class KthSmallestElement { |
| 11 | + public static void main (String[] args) { |
| 12 | + Scanner sc=new Scanner(System.in); |
| 13 | + PrintWriter out = new PrintWriter(System.out); |
| 14 | + int t=sc.nextInt(); |
| 15 | + |
| 16 | + while(t-->0) |
| 17 | + { |
| 18 | + int n=sc.nextInt(); |
| 19 | + |
| 20 | + int arr[]=new int[n]; |
| 21 | + |
| 22 | + for(int i=0;i<n;i++) |
| 23 | + arr[i]=sc.nextInt(); |
| 24 | + |
| 25 | + int k=sc.nextInt(); |
| 26 | + Solution ob = new Solution(); |
| 27 | + out.println(ob.kthSmallest(arr, 0, n-1, k)); |
| 28 | + } |
| 29 | + out.flush(); |
| 30 | + } |
| 31 | +} |
| 32 | +// } Driver Code Ends |
| 33 | + |
| 34 | + |
| 35 | +//User function Template for Java |
| 36 | + |
| 37 | +class Solution{ |
| 38 | + public static int kthSmallest(int[] arr, int l, int r, int k) |
| 39 | + { |
| 40 | + //Your code here |
| 41 | + PriorityQueue<Integer> pq = new PriorityQueue<>(); |
| 42 | + |
| 43 | + for (int j : arr) { |
| 44 | + pq.add(j); |
| 45 | + } |
| 46 | + int res = 0; |
| 47 | + for (int i = 0;i < k;i++) { |
| 48 | + res = pq.poll(); |
| 49 | + } |
| 50 | + return res; |
| 51 | + } |
| 52 | +} |
0 commit comments