Friday, October 13, 2023
HomeSoftware DevelopmentMax Heap in JavaScript - GeeksforGeeks

Max Heap in JavaScript – GeeksforGeeks


class MaxHeap {

 constructor() {

     this.heap = [];

 }

  

 

 getLeftChildIndex(parentIndex) { return 2 * parentIndex + 1; }

 getRightChildIndex(parentIndex) { return 2 * parentIndex + 2; }

  

 getParentIndex(childIndex) {

     return Math.ground((childIndex - 1) / 2);

 }

  

 hasLeftChild(index) {

     return this.getLeftChildIndex(index) < this.heap.size;

 }

  

 hasRightChild(index) {

     return this.getRightChildIndex(index) < this.heap.size;

 }

  

 hasParent(index) {

     return this.getParentIndex(index) >= 0;

 }

  

 leftChild(index) {

     return this.heap[this.getLeftChildIndex(index)];

 }

  

 rightChild(index) {

     return this.heap[this.getRightChildIndex(index)];

 }

  

 dad or mum(index) {

     return this.heap[this.getParentIndex(index)];

 }

  

 swap(indexOne, indexTwo) {

     const temp = this.heap[indexOne];

     this.heap[indexOne] = this.heap[indexTwo];

     this.heap[indexTwo] = temp;

 }

  

 peek() {

     if (this.heap.size === 0) {

         return null;

     }

     return this.heap[0];

 }

   

 

 

 

 take away() {

     if (this.heap.size === 0) {

         return null;

     }

     const merchandise = this.heap[0];

     this.heap[0] = this.heap[this.heap.length - 1];

     this.heap.pop();

     this.heapifyDown();

     return merchandise;

 }

  

 add(merchandise) {

     this.heap.push(merchandise);

     this.heapifyUp();

 }

  

 heapifyUp() {

     let index = this.heap.size - 1;

     whereas (this.hasParent(index) && this.dad or mum(index) < this.heap[index]) {

         this.swap(this.getParentIndex(index), index);

         index = this.getParentIndex(index);

     }

 }

  

 heapifyDown() {

     let index = 0;

     whereas (this.hasLeftChild(index)) {

         let largerChildIndex = this.getLeftChildIndex(index);

         if (this.hasRightChild(index) && this.rightChild(index) > this.leftChild(index)) {

             largerChildIndex = this.getRightChildIndex(index);

         }

         if (this.heap[index] > this.heap[largerChildIndex]) {

             break;

         } else {

             this.swap(index, largerChildIndex);

         }

         index = largerChildIndex;

     }

 }

   

 printHeap() {

     var heap =` ${this.heap[0]} `

     for(var i = 1; i<this.heap.size;i++) {

         heap += ` ${this.heap[i]} `;

     }

     console.log(heap);

 }

}

  

var heap = new MaxHeap();

  

heap.add(10);

heap.add(15);

heap.add(30);

heap.add(40);

heap.add(50);

heap.add(100);

heap.add(40);

  

heap.printHeap();

  

console.log(heap.peek());

console.log(heap.take away());

  

heap.printHeap();



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments