      1 var define = require("../define").define,
      2         Heap = require("./Heap"),
      3         base = require("../base");
      4
      5 /**
      6  * @class <p> Max Heap implementation, lowest value in heap is always at the root.</p>
      7  * </br>
      8  * <b>Performance</b>
      9  * <table>
     10  *     <tr><td></td><td>Best</td><td>Worst</td></tr>
     11  *     <tr><td>Insert</td><td>O(log n)</td><td>O(log n)</td></tr>
     12  *     <tr><td>Remove</td><td>O(log n)</td><td>O(log n)</td></tr>
     13  *     <tr><td>Peek</td><td>O(1)</td><td>O(1)</td></tr>
     14  *     <tr><td>Contains</td><td>O(n)</td><td>O(n)</td></tr>
     15  * <table>
     16  * @name MaxHeap
     17  * @augments comb.collections.Heap
     18  * @memberOf comb.collections
     19  */
     20 exports = module.exports = define(Heap, {
     21     instance : {
     22
     23
     24         __upHeap : function(index) {
     25             var heap = this.__heap;
     26             var node = heap[index];
     27             while (index >= 0) {
     28                 var parentIndex = this.__getParentIndex(index), parent = heap[parentIndex];
     29                 if (parent && parent.key < node.key) {
     30                     heap[index] = parent;
     31                     index = parentIndex;
     32                 } else {
     33                     break;
     34                 }
     35             }
     36             heap[index] = node;
     37         },
     38
     39         __downHeap : function(index) {
     40             var heap = this.__heap;
     41             var node = heap[index], length = heap.length;
     42             while (index < Math.floor(length / 2)) {
     43                 var leftIndex = this.__getLeftChildIndex(index),
     44                         rightIndex = this.__getRightChildIndex(index), left = heap[leftIndex], right = heap[rightIndex], child, childIndex;
     45                 if (rightIndex < length && right.key < left.key) {
     46                     childIndex = leftIndex;
     47                     child = left
     48                 } else {
     49                     childIndex = leftIndex;
     50                     child = heap[leftIndex];
     51                 }
     52                 if(child.key > node.key){
     53                     heap[index] = child;
     54                     index = childIndex;
     55                 }else{
     56                     break;
     57                 }
     58
     59             }
     60             heap[index] = node;
     61         }
     62
     63     }
     64 });
     65