ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Queue Implementation with Array

Java

Goal -- WPM

Ready
Exercise Algorithm Area
1public class ArrayQueue {
2
3private int[] queueArray;
4private int maxSize;
5private int front;
6private int rear;
7private int currentSize;
8
9/**
10* Constructs a queue with a specified maximum capacity.
11* This implementation uses a circular array to manage elements efficiently.
12*
13* @param capacity The maximum number of elements the queue can hold.
14*/
15public ArrayQueue(int capacity) {
16if (capacity <= 0) {
17throw new IllegalArgumentException("Capacity must be positive.");
18}
19this.maxSize = capacity;
20this.queueArray = new int[maxSize];
21this.front = 0;
22this.rear = -1; // Rear points to the last inserted element.
23this.currentSize = 0;
24}
25
26/**
27* Adds an element to the rear of the queue.
28* Handles wrap-around if the end of the array is reached.
29*
30* @param item The integer element to add.
31* @throws IllegalStateException if the queue is full.
32*/
33public void enqueue(int item) {
34if (isFull()) {
35throw new IllegalStateException("Queue is full. Cannot enqueue.");
36}
37// Move rear forward, wrapping around if necessary.
38rear = (rear + 1) % maxSize;
39queueArray[rear] = item;
40currentSize++;
41// System.out.println("Enqueued: " + item + ", Front: " + front + ", Rear: " + rear + ", Size: " + currentSize);
42}
43
44/**
45* Removes and returns the element from the front of the queue.
46* Handles wrap-around if the front reaches the end of the array.
47*
48* @return The element removed from the front of the queue.
49* @throws IllegalStateException if the queue is empty.
50*/
51public int dequeue() {
52if (isEmpty()) {
53throw new IllegalStateException("Queue is empty. Cannot dequeue.");
54}
55int removedItem = queueArray[front];
56// Move front forward, wrapping around if necessary.
57front = (front + 1) % maxSize;
58currentSize--;
59// System.out.println("Dequeued: " + removedItem + ", Front: " + front + ", Rear: " + rear + ", Size: " + currentSize);
60return removedItem;
61}
62
63/**
64* Returns the element at the front of the queue without removing it.
65*
66* @return The element at the front of the queue.
67* @throws IllegalStateException if the queue is empty.
68*/
69public int peek() {
70if (isEmpty()) {
71throw new IllegalStateException("Queue is empty. Cannot peek.");
72}
73return queueArray[front];
74}
75
76/**
77* Checks if the queue is empty.
78*
79* @return true if the queue is empty, false otherwise.
80*/
81public boolean isEmpty() {
82return (currentSize == 0);
83}
84
85/**
86* Checks if the queue is full.
87*
88* @return true if the queue is full, false otherwise.
89*/
90public boolean isFull() {
91return (currentSize == maxSize);
92}
93
94/**
95* Returns the current number of elements in the queue.
96*
97* @return The number of elements in the queue.
98*/
99public int size() {
100return currentSize;
101}
102
103/**
104* Helper method to display the current state of the queue.
105* Useful for debugging and understanding the circular buffer.
106*/
107public void displayQueue() {
108if (isEmpty()) {
109System.out.println("Queue is empty.");
110return;
111}
112System.out.print("Queue: [ ");
113int count = 0;
114int i = front;
115while (count < currentSize) {
116System.out.print(queueArray[i] + " ");
117i = (i + 1) % maxSize;
118count++;
119}
120System.out.println("] (Front: " + front + ", Rear: " + rear + ", Size: " + currentSize + ")");
121}
122
123public static void main(String[] args) {
124// Example usage
125ArrayQueue myQueue = new ArrayQueue(5);
126
127System.out.println("Is queue empty? " + myQueue.isEmpty()); // true
128System.out.println("Is queue full? " + myQueue.isFull()); // false
129System.out.println("Queue size: " + myQueue.size()); // 0
130
131myQueue.enqueue(10);
132myQueue.enqueue(20);
133myQueue.enqueue(30);
134myQueue.displayQueue(); // Queue: [ 10 20 30 ] (Front: 0, Rear: 2, Size: 3)
135
136System.out.println("Peek: " + myQueue.peek()); // 10
137System.out.println("Dequeue: " + myQueue.dequeue()); // 10
138myQueue.displayQueue(); // Queue: [ 20 30 ] (Front: 1, Rear: 2, Size: 2)
139
140myQueue.enqueue(40);
141myQueue.enqueue(50);
142myQueue.enqueue(60);
143myQueue.displayQueue(); // Queue: [ 20 30 40 50 60 ] (Front: 1, Rear: 0, Size: 5)
144
145System.out.println("Is queue full? " + myQueue.isFull()); // true
146
147// Attempt to enqueue when full
148try {
149myQueue.enqueue(70);
150} catch (IllegalStateException e) {
151System.out.println("Caught expected exception: " + e.getMessage());
152}
153
154System.out.println("Dequeue: " + myQueue.dequeue()); // 20
155System.out.println("Dequeue: " + myQueue.dequeue()); // 30
156myQueue.displayQueue(); // Queue: [ 40 50 60 ] (Front: 3, Rear: 0, Size: 3)
157
158myQueue.enqueue(70);
159myQueue.enqueue(80);
160myQueue.displayQueue(); // Queue: [ 40 50 60 70 80 ] (Front: 3, Rear: 2, Size: 5)
161
162while (!myQueue.isEmpty()) {
163System.out.println("Dequeue: " + myQueue.dequeue());
164}
165myQueue.displayQueue(); // Queue is empty.
166
167// Attempt to dequeue when empty
168try {
169myQueue.dequeue();
170} catch (IllegalStateException e) {
171System.out.println("Caught expected exception: " + e.getMessage());
172}
173
174// Test with capacity 1
175ArrayQueue singleCapacityQueue = new ArrayQueue(1);
176singleCapacityQueue.enqueue(100);
177singleCapacityQueue.displayQueue(); // Queue: [ 100 ] (Front: 0, Rear: 0, Size: 1)
178System.out.println("Peek: " + singleCapacityQueue.peek()); // 100
179System.out.println("Dequeue: " + singleCapacityQueue.dequeue()); // 100
180singleCapacityQueue.displayQueue(); // Queue is empty.
181}
182}
Algorithm description viewbox

Queue Implementation with Array

Algorithm description:

This Java code implements a Queue data structure using a fixed-size array, employing a circular buffer approach. It allows for efficient addition (enqueue) and removal (dequeue) of elements, managing the array indices to wrap around when the end is reached. This implementation is suitable for scenarios where a bounded queue is required, such as in producer-consumer problems or managing fixed-size buffers for data processing.

Algorithm explanation:

The `ArrayQueue` implementation has a time complexity of O(1) for enqueue, dequeue, peek, isEmpty, isFull, and size operations, assuming the array operations are O(1). This is because each operation involves a constant number of steps, regardless of the number of elements in the queue. The space complexity is O(n), where n is the maximum capacity of the queue, as it uses an array of fixed size to store the elements. Edge cases handled include a full queue (preventing enqueue) and an empty queue (preventing dequeue/peek), both of which throw `IllegalStateException`. The circular buffer logic is managed by the `front` and `rear` pointers and the modulo operator (`% maxSize`), which ensures that indices wrap around correctly. `currentSize` is used to track the number of elements, distinguishing between a full and empty queue when `front` and `rear` might otherwise be equal.

Pseudocode:

class ArrayQueue(capacity):
  array = new array of size capacity
  maxSize = capacity
  front = 0
  rear = -1
  currentSize = 0

  function enqueue(item):
    if isFull():
      throw error "Queue is full"
    rear = (rear + 1) % maxSize
    array[rear] = item
    currentSize++

  function dequeue():
    if isEmpty():
      throw error "Queue is empty"
    removedItem = array[front]
    front = (front + 1) % maxSize
    currentSize--
    return removedItem

  function peek():
    if isEmpty():
      throw error "Queue is empty"
    return array[front]

  function isEmpty():
    return currentSize == 0

  function isFull():
    return currentSize == maxSize