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

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

Priority Queue using Heaps

Updated 2026-04-20
3 min read

Introduction

In this tutorial, we will explore how to implement a Priority Queue using a Heap data structure. A priority queue is an abstract data type that generalizes the queue by allowing elements with different priorities to be enqueued and dequeued in order of their priority. Heaps are ideal for implementing priority queues because they provide efficient operations for insertion, deletion, and accessing the maximum or minimum element.

What is a Heap?

A heap is a complete binary tree where each node satisfies the heap property:

  • Max-Heap: For every node i, the value of i is greater than or equal to the values of its children.
  • Min-Heap: For every node i, the value of i is less than or equal to the values of its children.

Heaps are typically implemented using arrays due to their efficient memory usage and cache performance.

Implementing a Priority Queue with Heaps

Step 1: Define the Heap Structure

We'll start by defining a basic heap structure. For simplicity, we'll implement a Max-Heap. A Min-Heap can be implemented similarly by adjusting the comparison operators.

class MaxHeap {
    constructor() {
        this.heap = [];
    }

    // Helper methods will be defined here
}

Step 2: Inserting Elements

To insert an element into a max-heap, we add it to the end of the array and then "bubble up" the element to its correct position by comparing it with its parent.

class MaxHeap {
    constructor() {
        this.heap = [];
    }

    insert(value) {
        this.heap.push(value);
        this.bubbleUp();
    }

    bubbleUp() {
        let index = this.heap.length - 1;
        const element = this.heap[index];

        while (index > 0) {
            let parentIndex = Math.floor((index - 1) / 2);
            let parent = this.heap[parentIndex];

            if (element <= parent) break;

            this.heap[index] = parent;
            index = parentIndex;
        }

        this.heap[index] = element;
    }
}

Step 3: Extracting the Maximum Element

To extract the maximum element from a max-heap, we remove the root node and replace it with the last node in the array. Then, we "bubble down" the new root to its correct position.

class MaxHeap {
    constructor() {
        this.heap = [];
    }

    insert(value) {
        this.heap.push(value);
        this.bubbleUp();
    }

    bubbleUp() {
        let index = this.heap.length - 1;
        const element = this.heap[index];

        while (index > 0) {
            let parentIndex = Math.floor((index - 1) / 2);
            let parent = this.heap[parentIndex];

            if (element <= parent) break;

            this.heap[index] = parent;
            index = parentIndex;
        }

        this.heap[index] = element;
    }

    extractMax() {
        const max = this.heap[0];
        const end = this.heap.pop();

        if (this.heap.length > 0) {
            this.heap[0] = end;
            this.bubbleDown();
        }

        return max;
    }

    bubbleDown() {
        let index = 0;
        const length = this.heap.length;
        const element = this.heap[0];

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

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

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

            if (swap === null) break;

            this.heap[index] = this.heap[swap];
            index = swap;
        }

        this.heap[index] = element;
    }
}

Step 4: Peeking at the Maximum Element

To peek at the maximum element without removing it, we simply return the root of the heap.

class MaxHeap {
    constructor() {
        this.heap = [];
    }

    insert(value) {
        this.heap.push(value);
        this.bubbleUp();
    }

    bubbleUp() {
        let index = this.heap.length - 1;
        const element = this.heap[index];

        while (index > 0) {
            let parentIndex = Math.floor((index - 1) / 2);
            let parent = this.heap[parentIndex];

            if (element <= parent) break;

            this.heap[index] = parent;
            index = parentIndex;
        }

        this.heap[index] = element;
    }

    extractMax() {
        const max = this.heap[0];
        const end = this.heap.pop();

        if (this.heap.length > 0) {
            this.heap[0] = end;
            this.bubbleDown();
        }

        return max;
    }

    bubbleDown() {
        let index = 0;
        const length = this.heap.length;
        const element = this.heap[0];

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

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

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

            if (swap === null) break;

            this.heap[index] = this.heap[swap];
            index = swap;
        }

        this.heap[index] = element;
    }

    peek() {
        return this.heap[0];
    }
}

Real-World Applications

Priority queues using heaps have numerous real-world applications, including:

  • Operating Systems: Scheduling processes based on priority.
  • Network Routing: Determining the next hop in a network with different priorities.
  • Graph Algorithms: Dijkstra's algorithm for finding the shortest path.

Best Practices

  1. Choose the Right Heap Type: Use a Max-Heap if you need to extract the maximum element efficiently, and a Min-Heap if you need to extract the minimum element efficiently.
  2. Maintain Heap Property: Always ensure that the heap property is maintained after every insertion or deletion operation.
  3. Use Efficient Data Structures: Implementing heaps using arrays provides efficient memory usage and cache performance.

Conclusion

In this tutorial, we have learned how to implement a priority queue using a max-heap. Heaps provide efficient operations for insertion, deletion, and accessing the maximum element, making them ideal for implementing priority queues. By understanding the underlying principles of heaps and their applications, you can effectively use them in various real-world scenarios.

Feel free to experiment with the code examples provided and adapt them to your specific needs. Happy coding!


PreviousBinary HeapsNext Heap Sort Algorithm

Recommended Gear

Binary HeapsHeap Sort Algorithm