0

我正在尝试将值插入到最初为空的二进制堆中。

这是相关代码:

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;
    }

NullPointerException从 insert 方法中获得了 for 循环内的内容。这与我处理最初的空数组的方式有关吗?

这是初始化类:

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]);
        }
    }
}
4

2 回答 2

2

您还没有定义构造函数。

你写了...

public void minHeap()

这是一种方法,因为它具有“void”返回类型。

如果您放弃“空白”,它可能会有所帮助

于 2015-04-14T15:22:39.757 回答
0

除了此处的其他答案(指出您预期的构造函数没有正确的签名)之外,您似乎在这里会遇到问题:

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

在您第一次插入时,hole = 0但显然 x 等于,array[hole/2]因为hole/2计算结果为 0,因此此循环退出而不在 n = 1 上运行。

在您的第二次插入时,array[0] = x将吹走array[0]上一次插入时插入的任何内容,并将其替换为您的新x.

我可以看到你想要做什么,但它并不完全正确。

于 2015-04-14T15:35:42.933 回答