Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a max-heap using java

I am trying to create a Max-Heap in java using the following code:

public class Heapify {
// 16 14 10 8 7 9 3 2 4 1

    public static int[] Arr = {4, 1, 3, 2, 16, 9, 10, 14, 8, 7};
    public static int counter = 0;

    public static void main(String[] args) {
        int kk;
        for (kk = 0; kk <= Arr.length - 1; kk++) {
            heapM(Arr, kk);
        }

        for (int krk = 0; krk < Arr.length; krk++) {
            System.out.println(Arr[krk]);
        }



    }

    public static void heapM(int[] Arr, int i) {

        int largest;
        int left = i * 2;
        int right = i * 2 + 1;
        if (((left < Arr.length) && (Arr[left] > Arr[i]))) {
            largest = left;
        } else {
            largest = i;
        }

        if (((right < Arr.length) && (Arr[right] > Arr[largest]))) {
            largest = right;
        }
        if (largest != i) {
            swap(i, largest);


            heapM(Arr, largest);
        }
    }

    private static void swap(int i, int largest) {
        int t = Arr[i];
        Arr[i] = Arr[largest];
        Arr[largest] = t;

    }
}

The desired output should be :

16 14 10 8 7 9 3 2 4 1

Whereas I am getting

4 3 16 14 8 9 10 2 1 7

Can someone please help as to why the heap is not being built properly ?

Thanks

like image 721
Satya Avatar asked Feb 12 '26 05:02

Satya


2 Answers

I ran your code, and in addition to what Jodaka said, I found one more error

for (kk = 0; kk <= Arr.length - 1; kk++) {
        heapM(Arr, kk);
}

should be

for (kk = Arr.length -1; kk >= 0; kk--) {
        heapM(Arr, kk);
}

because when doing MaxHepify, you start from the end, and go backwards. and

 int left = i * 2;
 int right = i * 2 + 1;

should be, as Jodaka said

int left = 2*i+1;
int right = 2*i + 2;

I ran it here and the output is now correct

like image 171
La bla bla Avatar answered Feb 14 '26 19:02

La bla bla


I think your problem is here:

int left = i * 2;
int right = i * 2 + 1;

Since java arrays are zero-based, you are saying that the left child of 0 is 0 * 2 = 0! Fix your logic and see if that fixes your problem.

like image 38
Jodaka Avatar answered Feb 14 '26 19:02

Jodaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!