0

I'm trying to insert values into an initially empty binary heap.

This is the relevant code:

public class minHeap
{
    int[] array;
    int n;

    public void minHeap() 
    {
        array = new  int [16];  
        n = 0;
    }

    public void insert(int x) {
        //if (n == array.length - 1)
        //enlargeArray(array.length*2 + 1);

        // Hole is generated at end of array
        int hole = ++n;
        System.out.println("H"+hole);

        // Percolate up
        for (array[0] = x; x < array[hole/2]; hole /= 2)
            array[hole] = array[hole/2];

        // Insert new element
        array[hole] = x;
    }

I get the NullPointerException within the for loop from the insert method. Is it something with the way I'm dealing with the initially empty array?

Here's the initializing class:

public class BinaryHeap {

    public static void main(String[] args) 
    {
        int [] heapArray =  {62, 75, 81, 71, 66, 69, 72, 73, 83, 82, 67, 72, 81, 73, 69, 90};

        minHeap hp = new minHeap();

        for(int i = 0; i < heapArray.length; i++)
        {
            hp.insert(heapArray[i]);
        }
    }
}
resueman
  • 10,572
  • 10
  • 31
  • 45
itsmetheperson
  • 77
  • 1
  • 12
  • You need to see the difference between method and constructor. Thats where you made a mistake – Jimmy Apr 14 '15 at 15:23

2 Answers2

2

You have not defined a constructor.

You wrote...

public void minHeap()

This is a method because it has a "void" return type.

If you drop the "void" it might help

BretC
  • 4,141
  • 13
  • 22
0

In addition to the other answers here (pointing out that your intended constructor doesn't have the correct signature), it looks like you will have a problem here:

for (array[0] = x; x < array[hole/2]; hole /= 2)

On your first insert, hole = 0 but obviously x is equal to array[hole/2] since hole/2 evaluates to 0, so this loop exits without running on n = 1.

On your second insert, array[0] = x will blow away whatever had been inserted into array[0] on the previous pass, replacing it with your new x.

I can see what you're trying to do, but it ain't quite right.

Eric Hughes
  • 831
  • 6
  • 19