Queues By Jimmy M. Lu
Overview Definition Standard Java Queue Operations Implementation Queue at Work References
Definition A Queue is a data structure which stores items in a FIFO manner –FIFO stands for First In First Out. –Examples: A queue of people waiting in a line. A queue of documents waiting for the printer An abstract Queue is a queue where the elements can only be removed by the ‘dequeue’ operation
Standard Java Queue Operations Queue() –Constructs an empty Queue object boolean isEmpty() –Determines whether or not the queue is empty void enqueue( Object o ) –Adds a new element at the rear of the queue Object dequeue() –Removes and returns the element from the front of the queue
Implementation A queue uses a so-called circular array. –Briefly, a circular array is created with an index variable that increments as follows: I = (I+1) % MAX_SIZE Instance variables of a general class –private int front –private int rear –private size –private final int MAX_SIZE –private Object[] q
Implementation (Cont’) public void enqueue( Object o ) { if( size == MAX_SIZE ) throw new NoSuchElementException(); rear = (rear + 1) % MAX_SIZE; q[rear] = o; size++; } Runtime analysis: O(1)
Implementation (Cont’) public Object dequeue() { if( size == 0 ) throw new NoSuchElementException(); Object hold = q[front]; front = (front + 1) % MAX_SIZE; size--; return hold; } Runtime Analysis: O(1)
Queue at Work Breadth-First Search: (pseudo code) bfs (Graph G) { all vertices of G are first painted white the graph root is painted gray and put in a queue while (! Queue.isEmpty() ) { Queue.dequeue( a vertex u ) for all white successors v of u { v is painted gray Queue.enqueue(v); } u is painted black }
Queue at Work (Cont’) Given a graph, as shown on the right
Queue at Work (Cont’) All vertices are colored white
Queue at Work (Cont’)
FINISHED! Time Complexity = O(V+E)
References CS146 Textbook LDS210/queues.htmlhttp://ciips.ee.uwa.edu.au/~morris/Year2/P LDS210/queues.html algorithms/#bfshttp://renaud.waldura.com/portfolio/graph- algorithms/#bfs