Java find nth smallest element using priority queue heap

Code examples

0
0

java find nth smallest element using priority queue heap

public class MaxHeap {

    public static int  kthSmallestElement(int  k, int [] array){
        PriorityQueue<Integer> maxHeap = new  PriorityQueue<>(Collections.reverseOrder());
        int  length = array.length;
        for  (int  i = 0; i < length; i++){
            maxHeap.add(array[i]);
            if  (maxHeap.size() > k){
                maxHeap.poll();
            }
        }
        return  maxHeap.peek();
    }

    public static void  main(String[] args) {
        int [] array = {1, 3, 8, 9, 4, 7, 6};
        System.out .println(MaxHeap.kthSmallestElement(3, array));
    }
}

Similar pages

Similar pages with examples

In other languages

This page is in other languages

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................
Балгарскі
..................................................................................................................
Íslensk
..................................................................................................................