Queue Sort in C – Program to Sort Elements Using Queue

Sorting is a fundamental operation in computer science. While arrays and linked lists are commonly used for sorting, it’s also possible to sort elements using a queue. In this post, we’ll explore how to implement queue sort in C, which uses the basic queue operations—enqueue and dequeue—to sort elements in ascending order.

This approach helps in understanding both the working of queues and how sorting can be achieved using non-traditional data structures.


What is Queue Sort?

Queue sort refers to the process of arranging the elements of a queue in a sorted order using standard queue operations. Since a queue follows the FIFO (First In, First Out) principle, sorting with a queue often requires additional logic or a secondary queue.


C Program: Queue Sort in C

#include <stdio.h>
#include <stdlib.h>

#define SIZE 100

int queue[SIZE];
int front = -1, rear = -1;

void enqueue(int value) {
if (rear == SIZE - 1) {
printf("Queue Overflow\n");
return;
}
if (front == -1) front = 0;
queue[++rear] = value;
}

int dequeue() {
if (front == -1 || front > rear) {
printf("Queue Underflow\n");
return -1;
}
return queue[front++];
}

void sortQueue() {
int i, j, temp;
for (i = front; i < rear; i++) {
for (j = front; j < rear - (i - front); j++) {
if (queue[j] > queue[j + 1]) {
temp = queue[j];
queue[j] = queue[j + 1];
queue[j + 1] = temp;
}
}
}
}

void display() {
if (front == -1 || front > rear) {
printf("Queue is empty\n");
return;
}
for (int i = front; i <= rear; i++)
printf("%d ", queue[i]);
printf("\n");
}

int main() {
enqueue(30);
enqueue(10);
enqueue(50);
enqueue(20);
enqueue(40);

printf("Queue before sorting:\n");
display();

sortQueue();

printf("Queue after sorting:\n");
display();

return 0;
}

How It Works

  1. enqueue(): Adds elements to the queue.
  2. dequeue(): Removes elements from the queue.
  3. sortQueue(): Uses bubble sort logic on queue elements.
  4. display(): Prints the queue contents.

This method demonstrates sorting using queues without breaking their FIFO property by sorting elements internally using index access.


Why Learn Queue Sort in C?

  • Reinforces the concept of queues.
  • Shows how sorting logic can be applied on different data structures.
  • Helps in understanding data manipulation techniques.
Previous Article

Binary Search Tree in C – Create and Display Nodes

Next Article

Merge Sort in C – Step-by-Step Program with Explanation

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨