C Priority Queue

Intermediate
6 min read
Updated: Nov 2026
1 example

Serve the Highest Priority First

A priority queue removes the element with the highest priority, not the oldest. A simple implementation scans an array for the maximum on each dequeue (O(n)). A binary heap gives O(log n) for both insert and remove, which is why heaps are the standard implementation.

Remember
/* enqueue: append O(1)
   dequeue: find max priority O(n), remove it */

Cheat Sheet

Keep these facts handy while you work with Priority Queue in C.

TopicDetail
Array scanDequeue O(n)
HeapInsert and remove O(log n)
TiesNeed a rule (FIFO via sequence number)
UseSchedulers, Dijkstra, event simulation

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Queue Applications.

Example 1 — Task queue by priority

Higher numbers run first.

C
#include <stdio.h>

struct Task { const char *name; int pri; };

int main(void) {
    struct Task q[] = {
        {"write report", 2}, {"fix bug", 5}, {"lunch", 1}, {"deploy", 4}
    };
    int n = 4;

    while (n > 0) {
        int best = 0;
        for (int i = 1; i < n; i++)
            if (q[i].pri > q[best].pri) best = i;
        printf("%s (priority %d)\n", q[best].name, q[best].pri);
        q[best] = q[--n];
    }
    return 0;
}

How It Works

  1. Each round scans for the largest priority.
  2. The chosen task is removed by overwriting it with the last element.
  3. Tasks leave in priority order: 5, 4, 2, 1.

Edge Cases & Pitfalls

Check these before relying on Priority Queue in real programs.

ties

Unstable ties

Moving the last element into the gap can reorder equal priorities. Add a sequence number if order matters.

slow

O(n) dequeue

Use a heap for large queues.

Key Takeaways

  • Priority beats arrival.
  • Arrays: O(n) removal.
  • Heaps: O(log n).

One line: A priority queue removes the element with the highest priority, not the oldest.

Frequently Asked Questions

A queue where each element has a priority and the highest (or lowest) priority element is removed first.
A binary heap stored in an array, giving O(log n) insert and remove.
Continue with "C Queue Applications" next. Simulate round-robin scheduling with a queue. The C Queues hub lists every topic in order.

Next: Queue Applications

Simulate round-robin scheduling with a queue.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful