Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

heap javascript

class Heap{
constructor(capacity, heap_type)
  {
  
  this.heap_type = heap_type;
    this.count = 0;
    this.capacity = capacity;
    this.array = [];
    
  }
  
 
  Parent()
  {
  if(i<= 0 || i>=this.count)
  {return -1;}
    
    return i-1/2;
    
  }

  
  LeftChildren(i)
  {
  
  left = 2*i +1;
   if(left >= this.count)
   {
   return -1;
   }
    
    return left;
  
  }
  
  
  GetMaximum()
  {
    
  if(this.count == 0)
  {
    return -1;
  }
    
    return this.array[0];
  
  }
  
  
  PercolateDown(i){
var i, r, max, temp;
 l = LeftChild(i);
    r = RightChild(i);
    
    
    if(l !=  -1 && this.array[r] > this.array[max])
    {
    max = r;
    }
    
    if(max != i)
    {
    temp = this.array[i];
      this.array[i] = this.array[max];
      max = r;
    
    }
    
    if(max != i){
      
      temp = this.array[i];
 
      this.array[i] = this.array[max];
      this.array[max] = temp;
  }
  PercolateDown(max);
  }
  
  DeleteMax()
  {
   if(this.count == 0) 
   {
   return -1;
   }
  
    
    data = this.array[0];
    this.array[0] = this.array[this.count-1];
    
    
    this.count --;
    PercolateDown(0);
    
    return data;
    
  
  }
  
  Insert(data)
  {
    
    i; 
    if(this.count == this.capacity)
    {
    
     ResizeHeap();
    
    }
    
    
    this.count++;
    
    
    
    while(i>=0 && data  >this.array[(i-1)/2]){
      this.array[i] = this.array[(i-1)/2];
      i = i-1/2;
    }
    
    this.array[i] = data;
    
  }
  
  
  ResizeHeap()
  {
this.array = [...this.array]
    if(this.array == null)
    {console.log("Memory Error)
            return;     
                 }
    
  
    
    for(i =0; i<this.capacity; i++)
    {
    this.array[i] = array_old[i];
    }
    
    this.capacity *=2;
    array_old =null
  }
  
  Heapsort(A, n)
  {
  
    h = new Heap(n,0);
    
    var old_size, i, temp;
    BuildHeap(h, A, n);
    
    old_size = h.count;
    for(i = n-1 ; i>0; i--)
    {
    temp = h.array[0];
      h.array[0] = h.array[h.count-1];
      h.count--;
      h.PercolateDown(0);
      
      
    }
    
    
    h.count = old_size;
    
  
  }
  
}
 
PREVIOUS NEXT
Tagged: #heap #javascript
ADD COMMENT
Topic
Name
2+5 =