DSA Tutorial



QUEUE USING ARRAY


πŸ”² Queue using Array in DSA

A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. The element that is added first to the queue is the first one to be removed. A queue is often compared to a line at a ticket counter, where the first person to join the line is the first one to get served.

Basic Operations of Queue

The primary operations of a queue include:

  • Enqueue: Adds an element to the rear of the queue.
  • Dequeue: Removes an element from the front of the queue.
  • Front: Returns the front element of the queue without removing it.
  • isEmpty: Checks whether the queue is empty.
  • isFull: Checks if the queue is full (in case of a fixed-size queue).

Queue Implementation using Array

A queue can be implemented using an array. Here’s an example of how to implement a queue using an array in C:

#include 
#define MAX 5

int queue[MAX];
int front = -1;
int rear = -1;

void enqueue(int value) {
    if (rear == MAX - 1) {
        printf("Queue Overflow\n");
    } else {
        if (front == -1) front = 0;
        rear++;
        queue[rear] = value;
        printf("Enqueued %d\n", value);
    }
}

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

int peek() {
    if (front == -1 || front > rear) {
        printf("Queue is Empty\n");
        return -1;
    } else {
        return queue[front];
    }
}

int isEmpty() {
    return (front == -1 || front > rear);
}

int isFull() {
    return (rear == MAX - 1);
}

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

    printf("Dequeued: %d\n", dequeue());
    printf("Front: %d\n", peek());

    return 0;
}
      

Applications of Queue

Queues are used in several applications, including:

  • CPU Scheduling: CPU processes jobs in the order they arrive, often implemented using a queue.
  • Printer Queues: Documents are printed in the order they arrive in the queue.
  • Order Processing: Items in an order are processed based on their arrival in a queue.
  • Call Center Systems: Incoming calls are handled in the order they are received.
πŸš€ Advantages of Queues:
- Ensures fair handling of elements with the FIFO principle.
- Ideal for situations where order of processing matters.
- Efficient for implementing systems like task scheduling and printing.
πŸš€ Try Implementing Queue Operations:
- Implement a queue using a linked list and compare it with array-based implementation.
- Build a function that reverses a queue using two stacks.
- Experiment with a circular queue implementation to handle overflow and underflow efficiently.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review