DATA STRUCTURES PROGRAM • HEAPS, HASHING & DISJOINT SETS

Implement a Priority Queue with a Binary Heap

Learn how to implement a priority queue with a binary heap using a clear C program.

IntermediatePriority queueMax-heapExtract maximum

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
70 40 10

COMPLETE C PROGRAM

Complete C implementation

dsa-heap-priority-queue.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

void push(int heap[], int *size, int value)
{
    int position = (*size)++; heap[position] = value;
    while (position > 0) {
        int parent = (position - 1) / 2;
        if (heap[parent] >= heap[position]) return;
        int temporary = heap[parent]; heap[parent] = heap[position]; heap[position] = temporary;
        position = parent;
    }
}
int extract_max(int heap[], int *size)
{
    if (*size == 0) exit(EXIT_FAILURE);
    int result = heap[0]; heap[0] = heap[--(*size)];
    int position = 0;
    while (1) {
        int largest = position, left = 2 * position + 1, right = left + 1;
        if (left < *size && heap[left] > heap[largest]) largest = left;
        if (right < *size && heap[right] > heap[largest]) largest = right;
        if (largest == position) break;
        int temporary = heap[position]; heap[position] = heap[largest]; heap[largest] = temporary;
        position = largest;
    }
    return result;
}

int main(void)
{
    int heap[10], size = 0;
    push(heap, &size, 40); push(heap, &size, 10); push(heap, &size, 70);
    int first = extract_max(heap, &size);
    int second = extract_max(heap, &size);
    int third = extract_max(heap, &size);
    printf("%d %d %d\n", first, second, third);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

70 40 10
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Maintain max-heap order so the highest-priority value stays at the root.
  3. Display the computed result.

Maintain max-heap order so the highest-priority value stays at the root.

EFFICIENCY

Time and space complexity

Time complexity

O(log n) per operation

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.