title: Max heap in javascript?
body: <p>I am trying to write the function for creating a max heap in javascript 
  My current code is </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [5, 9, 6, 7, 1, 3, 8]
  var heap = []
  for (var i = 0; i &lt; arr.length; i++) {
    addtoheap(arr[i]);
  }
  
  function addtoheap(term) {
    heap.push(term);
  
    if (heap.length &gt; 1) {
      heapify(heap, (heap.length - 1))
    }
    console.log(heap);
  }
  
  function heapify(heap, i) {
    if (i == 0) {
      return;
    }
    if (heap[i] &gt; heap[Math.floor(i / 2)]) {
      var temp = heap[i];
      console.log("Swapping" + heap[i] + "--" + heap[Math.floor(i / 2)]);
      heap[i] = heap[Math.floor(i / 2)];
      heap[Math.floor(i / 2)] = temp;
      return heapify(heap, Math.floor(i / 2));
    } else {
      return;
    }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>And the output it gives is </p>
  
  <blockquote>
    <p>[ 5 ]<br>
    Swapping9--5<br>
    [ 9, 5 ]<br>
    Swapping6--5<br>
    [ 9, 6, 5 ]<br>
    Swapping7--6<br>
    [ 9, 7, 5, 6 ]<br>
    [ 9, 7, 5, 6, 1 ]<br>
    [ 9, 7, 5, 6, 1, 3 ]<br>
    Swapping8--6<br>
    Swapping8--7<br>
    [ 9, 8, 5, 7, 1, 3, 6 ]</p>
  </blockquote>
  
  <p>Not sure what I am doing wrong here ,can someone please point out the mistake in my logic ?</p>
  
  <p>Expected output : a max heap 
  [9,7,8,5,1,3,6]</p>