Monday, 24 May 2021

Find kth largest element in array in java using MaxHeap

 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;

    }


}


output:
[10, 3, 8, 2, 1, 4, 7]
[7, 3, 4, 2, 1, 8, 10]
8

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...