minHeap实现错误

时间:2016-05-12 17:09:02

标签: java data-structures min-heap

我正在尝试实现大小为k的minHeap。

虽然min-heap的属性在创建的数组中维护,但值不正确。

示例=> K = 5;输入:5,3,9,6,13,1;输出为:1 3 5 6 13,而正确的输出应为3,5,6,9,13

我的代码:

public class Heap {
    private int size;
    private static int[] heap;
    private int pos;
    private int requiredSize;

     Heap(int k){
         heap= new int[k+2];
         requiredSize=k+2;
         size=0;
         heap[0]=0;
     }

     public void insert(int e){
         heap[++size]=e;
         pos=size;
         while(heap[pos]<heap[getParent(pos)]){
             swap(pos,getParent(pos));
             correctChildren(pos);
             pos=getParent(pos);
         }
     }

     public int getMin(){
         return heap[1];
     }
     public void correctChildren(int pos){
        if(pos%2==0){
            if(pos+1<size && heap[pos]>heap[pos+1]){
                swap(pos,pos+1);
            }
        }
        else{
            if(heap[pos]<heap[pos-1]){
                swap(pos,pos-1);
            }
        }
     }
     public int getParent(int pos){
         return pos/2;
     }
     public int getRightChild(int pos){
         return 2*pos+1;
     }
     public int getLeftChild(int pos){
         return pos*2;
     }
     public void swap(int f, int s){
         int temp=heap[f];
         heap[f]=heap[s];
         heap[s]=temp;
     }

    public static int[] getHeap(){
        return heap;
    }
}

0 个答案:

没有答案