0

I am trying to represent an array in form of a Minimum-Heap. And I am facing a problem in one of the leaf nodes, where parent is greater than (12 grater than 6) the right child. I am not understanding what is wrong in my coding, please help.

Here is my code:

public class MinHeap {

public void heapify(int Array[], int i){

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

    int length=Array.length;

    if(left<length &&  Array[left]< Array[i] && Array[left]< Array[right])
        min=left;
    else if(right<length && Array[right]<Array[i] && Array[right]<Array[left])
        min=right;
    else min=i;

    if(min!=i){
        int temp=Array[i];
        Array[i] = Array[min];
        Array[min]=temp;
        heapify(Array,min);
    }
}

public void display(int Array[]){
    for(int i=0; i<Array.length; i++)
        System.out.print(Array[i]+" ");
}

public static void main(String[] args){
    int Array[]={2,1,4,5,6,100,0,9,8,3,12,32,6,7,1000,999,20};
    //int Array[]={1, 8, 9, 2, 10, 14, 3, 4, 7, 16};
    int length=Array.length;

    MinHeap object= new MinHeap();
    System.out.println(length);

    object.display(Array);
    System.out.println();

    for(int i=(length/2)-1;i>=0;i--){
        object.heapify(Array,i);

    }

    System.out.println();
    object.display(Array);
}

}

The output that I am getting is:

0 1 3 2 4 12 5 9 8 6 100 32 6 7 1000 999 20 
Johnny Sins
  • 71
  • 1
  • 10
  • Side note: i recommend to always use braces for if/then/else; even when you just do if () { one line } else { if { } and so on. Omitting the braces makes it much easier for you to get something wrong. Avoid that ... – GhostCat Mar 17 '16 at 00:12
  • You are trying to represent a min-heap as an array actually. – user207421 Mar 17 '16 at 01:15

2 Answers2

0

Try this.

static void heap(int[] a) {
    for (int i = 0; i < a.length; ++i) {
        while (true) {
            int p = (i - 1) / 2;
            if (a[p] <= a[i])
                break;
            int t = a[i];
            a[i] = a[p];
            a[p] = t;
            i = p;
        }
    }
}

and

int a[]={2,1,4,5,6,100,0,9,8,3,12,32,6,7,1000,999,20};
heap(a);
System.out.println(Arrays.toString(a));
// -> [0, 2, 1, 5, 3, 6, 4, 9, 8, 6, 12, 100, 32, 7, 1000, 999, 20]
0

Your children index is calculated wrong. You should use:

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

And the output will be:

0 1 2 5 3 6 4 9 8 6 12 32 100 7 1000 999 20

Nier
  • 638
  • 7
  • 15