Monday, 13 July 2020

Convert Min Heap into Max Heap

public class ConvertMinHeapToMaxheap {
    public static void main(String[] args) {
        ConvertMinHeapToMaxheap convertMinHeapToMaxheap = new ConvertMinHeapToMaxheap();
        int arr[]  ={3 ,5 ,9 ,6, 8, 20, 10, 12, 18, 9};
        for(int i = arr.length/2-1;i>=0;i--){
            convertMinHeapToMaxheap.heapify(arr,arr.length,i);
        }
        System.out.println(Arrays.toString(arr));
    }
    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(largest!=i){
            int temp = arr[largest];
            arr[largest] = arr[i];
            arr[i] = temp;
            heapify(arr,n,largest);
        }
    }
}

output: [20, 18, 10, 12, 9, 9, 3, 5, 6, 8]

No comments:

Post a Comment

links for Data Structure

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