0

I am trying to implement a minHeap of size k.

Although the properties of the min-heap are maintained within the array that is created, the values are not right.

Example=> k=5; input: 5,3,9,6,13,1 ; output is : 1 3 5 6 13 while the correct output should be 3,5,6,9,13

My Code:

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;
    }
}
dpm
  • 235
  • 2
  • 16
  • What output? The code you show doesn't produce any output. Your reported output is `1,3,5,6,13`, which is missing the `9`. Is that the actual output you're getting? Your expected output of `3,5,6,9,13` is missing the `1`. Is that a typo, or do you really not expect `1` to be output? Finally, there's no method in your class to remove and return the lowest value. Is that an oversight? – Jim Mischel May 12 '16 at 20:31
  • I have a main method that displays the result. Since the size of the heap is 5, only five elements should be displayed :3,5,6,9,13. Instead, 9 is being dropped and 1 made part of the heap. This is not a complete implementation of the heap, I am just implementing the insert method of a min-heap with size 5. – dpm May 12 '16 at 20:48
  • I think you need to spend some time single-stepping your code with a debugger to see what it's doing. – Jim Mischel May 12 '16 at 21:31
  • While finding the correct position of the element, the comparisons are only being made with the parent value and not the other siblings of the parent. This is resulting in the incorrect result. But I do not know how to accommodate that condition with this code or where to make a comparison with its siblings. – dpm May 12 '16 at 21:52
  • 1
    See my blog post at http://blog.mischel.com/2013/09/30/a-simple-heap-of-integers/. It's in C#, but you should be able to see how it's done. – Jim Mischel May 13 '16 at 03:58

0 Answers0