Queue Implementation using Array šŸš€

beginner
17 min

Queue Implementation using Array šŸš€

Welcome to another exciting tutorial! Today, we're going to learn how to implement a Queue using an Array šŸ“. This data structure is essential for handling tasks that come in sequentially but need to be processed in the order they arrive. Let's dive in!

What is a Queue? šŸ’”

A Queue is a collection of elements ordered in a sequential manner where the addition and removal of elements follows a specific rule: elements are added at the back (rear) and removed from the front (front). This order is often referred to as First-In-First-Out (FIFO).

Why use a Queue? šŸŽÆ

Queues are useful in various scenarios such as managing tasks in an operating system, handling requests in a web server, and optimizing graph traversal algorithms. Let's get our hands dirty and implement a Queue using an Array!

Queue Implementation šŸ“

Data Representation

To represent a Queue, we'll use an Array, and two additional variables: front and rear, which keep track of the position of the first and last elements in the queue, respectively.

python
queue = [] front = -1 rear = -1

Functions

We'll create three main functions: enqueue, dequeue, and is_empty.

  1. enqueue(item): Adds an item to the rear of the queue.
python
def enqueue(item): global queue, rear queue.append(item) rear += 1
  1. dequeue(): Removes and returns the front item from the queue.
python
def dequeue(): global queue, front, rear if is_empty(): return None front += 1 item = queue[front] queue[front] = None if front > rear: front = rear = -1 return item
  1. is_empty(): Checks if the queue is empty.
python
def is_empty(): return front == -1

Practical Example šŸ’¼

Imagine you're running a small print shop. Customers arrive and place orders one after the other. You will process the orders in the order they were received (FIFO).

python
queue = [] customers = ['Alice', 'Bob', 'Charlie', 'David', 'Eve'] for customer in customers: enqueue(customer) while not is_empty(): print('Printing:', dequeue())

Output:

Printing: Alice Printing: Bob Printing: Charlie Printing: David Printing: Eve

Quiz Time šŸ¤“

Quick Quiz
Question 1 of 1

What is the main difference between a Queue and a Stack?

Quick Quiz
Question 1 of 1

What happens if you try to `dequeue()` from an empty Queue?