public class FIndKthLargestEmement {
public static void main(String[] args) {
int[] arr = {4,1,7,2,3,8,10};
int n= arr.length;
for(int i=n/2-1;i>=0;i--){
heapify(arr,n,i);
}
System.out.println(Arrays.toString(arr));
int k = 2;
//run the loop k times from last index , move root element to ith and heapify the array to maintain maxheap
for(int i=n-1;i>=n-k;i--){
swap(arr,i,0);
heapify(arr,i,0); //i due to don't like to incluede already sorted element
}
System.out.println(Arrays.toString(arr));
System.out.println(arr[n-k]);
}
static void heapify(int[] arr, int n, int i){
int l = 2*i+1;
int r = 2*i+2;
int largest = i;
if(l<n){
if(arr[l]>arr[largest]){
largest = l;
}
}
if(r<n){
if(arr[r]>arr[largest]){
largest = r;
}
}
//if value get updated
if(largest!=i){
swap(arr,i,largest);
heapify(arr,n,largest);
}
}
static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] =arr[j];
arr[j]=temp;
}
}
No comments:
Post a Comment