title: Building a min heap using java
body: <p>I tried to build a minHeap using java, this is my code:</p>
  
  <pre><code>public class MyMinHeap {
  
      private ArrayList&lt;Node&gt; heap;
  
      public MyMinHeap() {
          heap = new ArrayList&lt;Node&gt;();
      }
  
      public MyMinHeap(ArrayList&lt;Node&gt; nodeList) {
          heap = nodeList;
          buildHeap();
      }
  
      public void buildHeap() {
          int i = heap.size() / 2;
          while (i &gt;= 0) {
              minHeapify(i);
              i--;
          }
      }
  
      public Node extractMin() {
          if (heap.size() &lt;= 0) return null;
          Node minValue = heap.get(0);
          heap.set(0, heap.get(heap.size() - 1));
          heap.remove(heap.size() - 1);
          minHeapify(0);
          return minValue;
      }
  
      public String toString() {
          String s = "";
          for (Node n : heap) {
              s += n + ",";
          }
          return s;
      }
  
      public void minHeapify(int i) {
          int left = 2 * i + 1;
          int right = 2 * i + 2;
  
          int smallest = i;
  
          if (left &lt; heap.size() - 1 &amp;&amp; lessThan(left, smallest))
              smallest = left;
  
          if (right &lt; heap.size() - 1 &amp;&amp; lessThan(right, smallest))
              smallest = right;
  
          if (smallest != i) {
              swap(smallest, i);
              minHeapify(smallest);
          }
      }
  
      private void swap(int i, int j) {
          Node t = heap.get(i);
          heap.set(i, heap.get(j));
          heap.set(j, t);
      }
  
      public boolean lessThan(int i, int j) {
          return heap.get(i)
                     .compareTo(heap.get(j)) &lt; 0;
      }
  
      public static void main(String[] args) {
          char[] chars = {'a', 'b', 'c', 'd', 'e', 'f'};
          int[] freqs = {45, 13, 12, 16, 9, 5};
  
          ArrayList&lt;Node&gt; data = new ArrayList&lt;Node&gt;();
          for (int i = 0; i &lt; chars.length; i++) {
              data.add(new Node(chars[i], freqs[i]));
          }
  
          MyMinHeap heap = new MyMinHeap(data);
  
          System.out.println("print the heap : " + heap);
          for (int i = 0; i &lt; chars.length; i++) {
              System.out.println("Smallest is :" + heap.extractMin());
          }
  
      }
  }
  </code></pre>
  
  <p>The output should be:5,9,12,13,16,45,</p>
  
  <p>but what I got is : 9,13,12,16,45</p>
  
  <p>I have debugged this but still can't figure out, anybody help? thanks a lot.</p>