package java_programs;
import java.util.*;

/**
 *
 * @author derricklin
 */
public class KHEAPSORT {
    public static ArrayList<Integer> kheapsort(ArrayList<Integer> arr, int k) {
        PriorityQueue<Integer> heap = new PriorityQueue<>();
        for (Integer v : arr.subList(0, Math.min(k, arr.size()))) {
            heap.add(v);
        }

        ArrayList<Integer> output = new ArrayList<>();
        for (Integer x : arr) {
            heap.add(x);
            if (heap.size() > k) {
                Integer popped = heap.poll();
                output.add(popped);
            }
        }

        while (!heap.isEmpty()) {
            output.add(heap.poll());
        }

        return output;
    }
}