So I'm a total newbie to Java and coding in general, having just learnt Big-O as well. I came across this on the internet yesterday (http://www.dsalgo.com/2013/02/MaxKUsingMinHeap.php.html), and would like to know if the complexity analysis [O(n log k)] the code below is correct. Does it also include the worst case scenario? I'd really appreciate if someone could go through this and explain.
import java.util.PriorityQueue;
public class MaxKUsingMinHeap {
public static void main(String[] args) {
int[] arr = {
3, 46, 2, 56, 3, 38, 93, 45, 6, 787, 34, 76, 44, 6, 7, 86, 8, 44, 56
};
int[] result = getTopElements(arr, 5);
for (int i : result) {
System.out.print(i + ",");
}
}
public static int[] getTopElements(int[] arr, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
for (int i = 0; i < arr.length; ++i) {
int currentNum = arr[i];
if (minHeap.size() < k) {
minHeap.add(currentNum);
}
else if (currentNum > minHeap.peek())
{
minHeap.poll();
minHeap.add(currentNum);
}
}
int[] result = new int[minHeap.size()];
int index = 0;
while (!minHeap.isEmpty()) {
result[index++] = minHeap.poll();
}
return result;
}
}