Sebas Silva
Sebas Silva

Reputation: 115

Why a fixed array is being modified?

I was seeing this video on youtube: https://www.youtube.com/watch?v=8K1rt6v5mJ4&list=PLsyeobzWxl7oRKwDi7wjrANsbhTX0IK0J&index=14 to learn data structures on Java, more specifically the queue, copying exactly what the author is doing, in the min 9:46 his program prints 6 elements, when the program only has 5 elements as the limit, he says is the loop, but I didn't understand why.

it was fixed by implementing isFull() and isEmpty() methods, but I didn't quite understand why It happened in the first place.

public class Queue {
    private int [] q=new int[5];
    private int size=0;
    private int front=0;
    private int rear=0;
    private int total=5;

    public void enqueue(int item)
    {
        q[rear]=item;
        rear=(rear+1)%total;
        size=size+1;   
    }
    public int dequeue()
    {       
       int item=q[front];
       front=(front+1)%total;
       size=size-1;
       return item;
     }

     public void show()
     {
         System.out.print("Elements: ");

         for(int i = 0; i < size; i++)
         {
             System.out.print(q[(front+i)%total]+" ");
             System.out.println();
         }
         for(int n:q)
         {
             System.out.print(n+" ");
         }
     }
 }

The test was with this values:

intqueue.enqueue(5);
intqueue.enqueue(2);
intqueue.enqueue(7);
intqueue.enqueue(3);

intqueue.dequeue();
intqueue.dequeue();

intqueue.enqueue(9);
intqueue.enqueue(1);
intqueue.enqueue(19);
intqueue.enqueue(15);

and the result was:

for the first for: 15 3 9 1 19 15
for the entire queue: 1 19 15 3 9

Upvotes: 0

Views: 67

Answers (1)

racraman
racraman

Reputation: 5034

The test values you show have 8 enqueues and 2 dequeues. That means the sum total is that you have added 6 elements (so size will == 6), into a structure that only has the capacity to hold 5.

Given the order of operations, if the queue array was large enough (say int[10] instead of int[5]), then the queue would have held :

  7, 3, 9, 1, 19, 15

However, since the queue is only 5 long, the first element (the 7) would have been overwritten by the last (the 15), resulting in the 5 array elements holding just :

3, 9, 1, 19, 15

Since size == 6, the output also loops around and so prints that latest element twice (first and last).

Upvotes: 2

Related Questions