codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

45 / 65 topics
45Heap Data Structure46Binary Heaps47Priority Queue using Heaps48Heap Sort Algorithm
Tutorials/Data Structures & Algorithms/Heap Data Structure
🧮Data Structures & Algorithms

Heap Data Structure

Updated 2026-04-20
3 min read

Heap Data Structure

Introduction

A heap is a specialized tree-based data structure that satisfies the heap property, which ensures that for any given node \( i \), the value of \( i \) is greater than or equal to (in a max heap) or less than or equal to (in a min heap) the values of its children. This property allows heaps to efficiently implement priority queues and perform operations like insertion, deletion, and finding the maximum or minimum element in logarithmic time.

Types of Heaps

  1. Max Heap: In a max heap, for every node \( i \), the value of \( i \) is greater than or equal to the values of its children.
  2. Min Heap: In a min heap, for every node \( i \), the value of \( i \) is less than or equal to the values of its children.

Representation

Heaps are typically represented as binary trees but can also be implemented using arrays. The array representation makes it easy to calculate the parent and child indices:

  • Parent Index: For a node at index \( i \), the parent is at index \( \lfloor (i - 1) / 2 \rfloor \).
  • Left Child Index: For a node at index \( i \), the left child is at index \( 2i + 1 \).
  • Right Child Index: For a node at index \( i \), the right child is at index \( 2i + 2 \).

Operations

Insertion

To insert an element into a heap, follow these steps:

  1. Add the new element to the end of the array.
  2. Bubble up the new element by comparing it with its parent and swapping if necessary until the heap property is restored.
function insert(heap, value) {
  heap.push(value);
  let index = heap.length - 1;
  while (index > 0) {
    const parentIndex = Math.floor((index - 1) / 2);
    if (heap[parentIndex] >= value) break;
    [heap[index], heap[parentIndex]] = [heap[parentIndex], heap[index]];
    index = parentIndex;
  }
}

Deletion

To delete the root element from a max heap, follow these steps:

  1. Replace the root with the last element in the array.
  2. Bubble down the new root by comparing it with its children and swapping if necessary until the heap property is restored.
function extractMax(heap) {
  const max = heap[0];
  const end = heap.pop();
  if (heap.length > 0) {
    heap[0] = end;
    let index = 0;
    const length = heap.length;
    const element = heap[0];

    while (true) {
      let leftChildIndex = 2 * index + 1;
      let rightChildIndex = 2 * index + 2;
      let leftChild, rightChild;
      let swap = null;

      if (leftChildIndex < length) {
        leftChild = heap[leftChildIndex];
        if (leftChild > element) {
          swap = leftChildIndex;
        }
      }

      if (rightChildIndex < length) {
        rightChild = heap[rightChildIndex];
        if (
          (swap === null && rightChild > element) ||
          (swap !== null && rightChild > leftChild)
        ) {
          swap = rightChildIndex;
        }
      }

      if (swap === null) break;
      [heap[index], heap[swap]] = [heap[swap], heap[index]];
      index = swap;
    }
  }
  return max;
}

Finding the Maximum/Minimum

  • Max Heap: The maximum element is always at the root.
  • Min Heap: The minimum element is always at the root.

Best Practices

  1. Use Arrays for Implementation: Arrays provide efficient access to elements and are easier to manage than linked lists.
  2. Heapify Operation: For building a heap from an array, use the heapify operation, which ensures that each subtree satisfies the heap property.
  3. Balance Operations: Ensure that operations like insertion and deletion maintain the balance of the heap.

Real-World Applications

  1. Priority Queues: Heaps are used to implement priority queues where elements with higher priority are served before those with lower priority.
  2. Graph Algorithms: Dijkstra's algorithm for finding the shortest path uses a min heap to efficiently extract the minimum distance node.
  3. Heap Sort: A comparison-based sorting algorithm that uses a binary heap data structure.

Conclusion

Heaps are powerful data structures that provide efficient ways to manage and retrieve elements based on priority. Understanding their properties, operations, and applications is crucial for any software engineer or data scientist working with algorithms and data management systems. By mastering heaps, you can optimize your code for better performance in various computational tasks.


PreviousStrassen's Matrix MultiplicationNext Binary Heaps

Recommended Gear

Strassen's Matrix MultiplicationBinary Heaps