插入和删除最大堆java

时间:2013-11-11 02:25:08

标签: java arrays algorithm sorting heap

我编写了一个由包含两个东西的节点构成的最大堆的java实现,一个字符串和一个可以从每个节点访问的double值。它们应该按其双重值的等级插入。我不确定它的插入或移除是否工作不正常,但当我尝试从堆中删除前五个最大值时,我没有得到我应该得到的东西。打嗝的任何想法?这些方法中包括isfull和isempty来测试它是空的或者当然是完全的基本情况...... Count是数组中节点的总数(堆是数组)。

public boolean insert(String W, double R){

    HeapNode word = new HeapNode(W,R);
    if (isFull()){
        return false;
    }
    else {
        count++;
        heap[count - 1] = word;
        siftUp(count - 1);
    }
    System.out.println("Added");
    return true;
}

public boolean siftUp(int place){

    int parentNode;
    HeapNode tmp;
    if (place != 0) {
        //parent node of place
        //parentNode = getParentNode(place);
        parentNode = ((place-1) / 2);
        if (heap[parentNode].getDouble() < heap[place].getDouble()) {
              tmp = heap[parentNode];
              heap[parentNode] = heap[place];
              heap[place] = tmp;
              siftUp(parentNode);
        }
    }
    return true;
}

这是插入,现在是删除:

public HeapNode remove(){
    HeapNode maxValue;
    if (isEmpty()){
        return null;
    }
    else{
        // Where does the max value always reside? 
        maxValue = heap[0]; 

        // What value will take the root? Last one. 

        heap[0] = heap[count-1]; 
        count--; ;

        // Begin percolate down at index of root 
        int hole = 0; 

        int child; 
        HeapNode temp = heap[hole]; 

        while( hole * 2 + 1 < count) 
        { 
         // Index of left child of node in hole index 
         child = 2 * hole + 1; 

         //find greater child
         if(child != count && (heap[child + 1].getDouble()) > (heap[child].getDouble())) 
            child++; //swap index

         if((heap[child].getDouble()) > (temp.getDouble())) //last comparison
            heap[hole] = heap[child];
         else 
            break; 

         hole = child; 
        } 
        heap[hole] = temp; 
    }
    return maxValue;
}

我正在使用的测试用例。根据其双精度值按此顺序输入节点: 1.0,0.8,0.9,0.8,1.0,0.6,1.0,1.0,0.8,1.0,0.7,1.0,0.8 删除前五个我应该得到所有1.0的?我得到1.0,0.8,1.0,0.7,1.0五。

2 个答案:

答案 0 :(得分:1)

我可以发现2个错误。

  1. 您有parentNode = (place / 2);
    siftup方法中。显然你使用的是基于0的数组索引,因此节点0应该有1和2作为子节点,但这个等式给出1作为2的父节点。
    将其更改为parentNode = ((place-1) / 2);

  2. 另一个是下一行:
    if (heap[parentNode].getDouble() > heap[place].getDouble())
    这会将min节点冒泡到顶部,而不是最大节点。

答案 1 :(得分:0)

您遇到的另一个问题是remove方法中的此声明:

 //find greater child
     if(child != count && (heap[child + 1].getDouble()) > (heap[child].getDouble())) 
        child++; //swap index

在这里,您已经知道child < count,因为您在循环中测试了它。但是如果(child+1) == count,那么你正在测试堆中前一个最后一个元素的当前元素。

我认为你想要的是:

if ((child < count-1) && (heap[child + 1].getDouble()) > (heap[child].getDouble())) 
相关问题