VOOZH about

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

⇱ Heap in JavaScript - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Heap in JavaScript

Last Updated : 23 Jul, 2025

A Heap is a special Tree-based Data Structure that has the following properties.

AMin-Heap is a complete binary tree in which the value in each node is smaller than all of its descendants.


A Max-Heap is a complete binary in which root node must be the greatest among all its descendant nodes and the same thing must be done for its left and right sub-tree also.

Min Heap

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

👁 Min Heap in JavaScript
Min Heap in JavaScript

Let us go through the representation of Min heap. So basically Min Heap is a complete binary tree. A Min heap is typically represented as an array. The root element will be at Arr[0]. For any ith node, i.e., Arr[i] 

  • Arr[(i -1) / 2] returns its parent node.
  • Arr[(2 * i) + 1] returns its left child node.
  • Arr[(2 * i) + 2] returns its 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, and 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 Min Heap data structure.


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

Max Heap

Please refer Max Heap in JavaScript for details.

Comment
Article Tags:
Article Tags: