public static int[] findKLargest(int[] arr,int k)
{
int[] result = new int[k];
for(int i=(arr.length-1)/2; i>=0; i--) {
maxHeapify(arr, i);
}
result = Arrays.copyOf(arr, k);
return result;
}
private static void maxHeapify(int[] maxHeap, int index) {
int largerIndex = index;
int leftIndex = index * 2 + 1;
int rightIndex = index * 2 + 2;
if(leftIndex < maxHeap.length && maxHeap[leftIndex] > maxHeap[largerIndex]) {
largerIndex = leftIndex;
}
if(rightIndex < maxHeap.length && maxHeap[rightIndex] > maxHeap[largerIndex]) {
largerIndex = rightIndex;
}
if(index == largerIndex) return;
swap(maxHeap, index, largerIndex);
maxHeapify(maxHeap, largerIndex);
}
private static void swap(int[] maxHeap, int first, int second) {
int temp = maxHeap[first];
maxHeap[first] = maxHeap[second];
maxHeap[second] = temp;
}