VOOZH about

URL: https://www.geeksforgeeks.org/javascript/max-heap-in-javascript/

⇱ Max Heap in JavaScript - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Max Heap in JavaScript

Last Updated : 23 Jul, 2025

A max-heap is a complete binary tree in which the value in each node is greater than the values in the descendant nodes.

Mapping the elements of a heap into an array is trivial: if a node is stored at index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.

👁 Max Heap in JavaScript
Max Heap in JavaScript


A-Max Heap is a Complete Binary Tree. A-Max heap is typically represented as an array. The root element will be at Arr[0]. Below table shows indexes of other nodes for the ith node, i.e., Arr[i]: 

Arr[(i-1)/2] Returns the parent node. 
Arr[(2*i)+1] Returns the left child node. 
Arr[(2*i)+2] Returns the right child node.

  • Heapify: a process of creating a heap from an array.
  • Insertion: process to insert an element in existing heap time complexity O(log N).
  • Deletion: deleting the top element of the heap or the highest priority element, and then organizing the heap and returning the element with time complexity O(log N).
  • Peek: to check or find the most prior element in the heap, (max or min element for max and min heap).

Explanation: Now let us understand how the various helper methods maintain the order of the heap

  • The helper methods like rightChild, leftChild, parent  help us to get the element and its children at the specified index.
  • The add() and remove() methods handle the insertion and deletion process
  • The heapifyDown() method maintains the heap structure when an element is deleted.
  • The heapifyUp() method maintains the heap structure when an element is added to the heap. 
  • The peek() method returns the root element of the heap and swap() method interchanges value at two nodes.

Example: In this example, we will implement the Max Heap data structure.


Output
 100 40 50 10 30 15 40 
100
100
 50 40 40 10 30 15 

Please refer Min Heap in JavaScript for min heap implementation.


Comment
Article Tags:
Article Tags: