title: Min heap in javascript
body: <p>Hey I tried to implement a min heap in javascript, but i had a question regarding the algorithm for remove min. I'm using an array to represent the heap internally. When I'm percolating downwards, what should be the stopping condition? In my code I have it at 2 * k &lt;= this.size so it would travel down to potentially the very last element, but it doesn't feel "correct", is there a better stopping condition? Thanks in advance!</p>
  
  <pre><code>this.removeMin = function () {
      //replace root with last element and percolate downwards
      var min = this._heap[1],
          k,
          left,
          right;
  
      this._heap[1] = this._heap.pop();
      this.size--;
      k = 1;
  
      while ( ( 2 * k ) &lt;= this.size) {
          left = 2 * k;
          right = 2 * k + 1;
  
          if (this._heap[k] &gt; this._heap[left] &amp;&amp; this._heap[k] &gt; this._heap[right]) {
              if (this._heap[left] &lt;= this._heap[right]) {
                  swap(this._heap, k, left);
                  k = left;
              } else {
                  swap(this._heap, k, right);
                  k = right;
              }
          } else if (this._heap[k] &gt; this._heap[left]) {
              swap(this._heap, k, left);
              k = left;
          } else {
              swap(this._heap, k, right);
              k = right;
          }
      }
  
      return min;
  };
  </code></pre>