DATA STRUCTURES PROGRAM • QUEUES & DEQUES
Implement a Priority Queue Using an Ordered Array
Learn how to implement a priority queue using an ordered array using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
30(p3) 10(p2) 20(p1)
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
struct Item { int value; int priority; };
void insert(struct Item queue[], int *count, int value, int priority)
{
int index = *count;
while (index > 0 && queue[index - 1].priority > priority) {
queue[index] = queue[index - 1]; index--;
}
queue[index] = (struct Item){value, priority};
(*count)++;
}
int main(void)
{
struct Item queue[6];
int count = 0;
insert(queue, &count, 10, 2);
insert(queue, &count, 20, 1);
insert(queue, &count, 30, 3);
while (count > 0) {
struct Item item = queue[--count];
printf("%d(p%d) ", item.value, item.priority);
}
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
30(p3) 10(p2) 20(p1)
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Keep entries ordered by priority so the highest-priority item is removed from the end.
- Display the computed result.
Keep entries ordered by priority so the highest-priority item is removed from the end.
EFFICIENCY
Time and space complexity
Time complexity
O(n) insertion, O(1) removal
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.
