Top Banner
Data Structures, Algorithms Queue C# Prof Hesham Arafat Ali
34
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Queue data structure

Data Structures, AlgorithmsQueue C#

Prof Hesham Arafat Ali

Page 2: Queue data structure

2

Queues Everywhere!

Page 3: Queue data structure

Physical Nature of the Queue Physical Nature of the Queue

Page 4: Queue data structure

Physical Nature of the QueuePhysical Nature of the Queue

Page 5: Queue data structure

5

Queue ApplicationsQueue ApplicationsReal-World ApplicationsReal-World Applications

Buy a movie ticketCheck out at a bookstoreBank / ATMCall an airlineCashier lines in any store

 Computer Science ApplicationsComputer Science ApplicationsOS task schedulingPrint lines of a documentPrinter shared between computersConvert digit strings to decimalShared resource usage (CPU, memory access, …)

Page 6: Queue data structure

QueuesQueues

A queue represents a waiting list A queue can be viewed as a special type

of list, where the elements are inserted into the end (tail) of the queue, and are accessed and deleted from the beginning (head) of the queue

6

Data1 Data2

Data1 Data1 Data2 Data3

Data1 Data2 Data3

Data2 Data3

Data1

Data3

Data2 Data3

Page 7: Queue data structure

Queue Abstract Data Type

ADT queue FIFO(First In First Out)ordered listall insertions are made at one end called “rearrear”all deletions are made at the other end called “frontfront”

inserting and deleting elements in queue

rearArearB

A

rearCBA

rearDCBA

rearDCB frontfrontfrontfront

front

Page 8: Queue data structure

Queue DefinitionQueue DefinitionIs a container which provides exactly one method, enqueueenqueue, for putting objects at the rear of the container, and one method, dequeuedequeue, for taking objects out of the container at the front.

container of objects that are inserted and removed according to the first-in first-out (FIFOFIFO) principle.

Queue A data structure in which elements are added to the rear and removed from the front; a "first in, first out" (FIFO)

Page 9: Queue data structure

MethodsMethods

enqueue(o)enqueue(o) insert object o at the rear ofthe queueInput: Object; Output: None

dequeue() dequeue() removes and return the object at the front of the queue; an error occurs if the

Input: None; Output: Object

Page 10: Queue data structure

MethodsMethods

size( ) size( ) return the number of objects in the queue

Input: None; Output: Integer

isEmpty( ) isEmpty( ) return a Boolean indicating ifthe queue is empty Input: None; Output: Boolean

front( ) front( ) returns the front object in the queue, without removing it; an error occurs if the queue is empty

Input: None; Output: Object

Page 11: Queue data structure

Array ImplementationArray Implementation

The easiest implementation also keeps track of the number of items in the queue and the index of the first element (at the front of the queue), the last element (at the rear).

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

4 8 6

sizesize3

firstfirst0

lastlast2

Page 12: Queue data structure

A Dequeue OperationA Dequeue Operation

When an element leaves the queue, size is decremented, and first changes, too.

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

4 8 6

sizesize2

firstfirst1

lastlast2

Page 13: Queue data structure

An Enqueue OperationAn Enqueue Operation

When an element enters the queue, size is incremented, and last changes, too.

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

28 6

sizesize3

firstfirst1

lastlast3

Page 14: Queue data structure

At the End of the ArrayAt the End of the Array

There is special behavior at the end of the array. For example, suppose we want to add a new element to this queue, where the last index is [5]:

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ]

2 16

sizesize3

firstfirst3

lastlast5

Page 15: Queue data structure

At the End of the ArrayAt the End of the Array

The new element goes at the front of the array (if that spot isn’t already used):

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ]

2 16

sizesize4

firstfirst3

lastlast0

4

Page 16: Queue data structure

Queue Illustration

enqueue(D)

enqueue(A)

dequeue( )

Page 17: Queue data structure

enqueue(T)

enqueue(U)

enqueue(M)

front( )

Page 18: Queue data structure

isEmpty( )

size( )

Page 19: Queue data structure

Queue (Array Implementation)

Page 20: Queue data structure

Queue (Array Implementation)Queue (Array Implementation)

Page 21: Queue data structure

Queue (Array Implementation)

Page 22: Queue data structure

Sample Queue Operation

Page 23: Queue data structure

Queue (Array Implementation)

disadvantage: Moving the elements will require O(n) time

Page 24: Queue data structure

Queue (Array Implementation)

Page 25: Queue data structure

Queue (Array Implementation)

Page 26: Queue data structure

Linked List ImplementationLinked List Implementation

10

15

7

null

13

A queue can also be implemented with a linked list with both a head and a tail pointer.

head_ptrtail_ptr

Page 27: Queue data structure

Queue (Array Implementation)

f is an index to cell of Q that stores the first

element of the queue (unless the queue is empty: f = r)r is an index to the next available array cell in

Q initially, f = r = 0.

Page 28: Queue data structure

To get the value of r, we compute: (r+1) mod N

To get the value of f, we compute: (f+1) mod N

To get the size of the Queue: (N-f+r) mod N

Page 29: Queue data structure

29

ADT QueueSpecification:

Operations• Create an empty queue• Create a copy of a queue• Destroy a queue• Check if a queue is empty / Full• Enqueue (Enq, Enque, Add, Insert) new element to the back (rear)• Dequeue (Deq, Deque, Remove, Serve, Delete) an element from

the front• Retrieve an element from a queue

Like the stack, if we need to modify an item in the queue, we must remove it, change its contents, and then add it back to the queue

Page 30: Queue data structure

Enqueue and dequeueusing System; using System.Collections;   class MainClass {  public static void Main() {     Queue q = new Queue();     q.Enqueue(1);     q.Enqueue(2);     q.Enqueue(3);     q.Enqueue(4);     Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");     Console.WriteLine();             Console.Write("Dequeue -> ");     int a = (int) q.Dequeue();     Console.WriteLine(a);     Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");     Console.WriteLine();           } }

queue: 1 2 3 4Dequeue -> 1queue: 2 3 4

Page 31: Queue data structure

Put elements into a queue using System;using System.Collections;using System.Collections.Generic;using System.Text;

class Program {    static void Main(string[] args) {        Queue alphabet = new Queue();        alphabet.Enqueue("A");        alphabet.Enqueue("B");        alphabet.Enqueue("C");

        Console.Write("First Iteration: ");

        foreach (string item in alphabet) {            Console.Write(item);        }

        Console.WriteLine("\nItem pulled from collection: " +           alphabet.Dequeue().ToString());        Console.Write("Second iteration: ");

        foreach (string item in alphabet) {            Console.Write(item);        }   } }

First Iteration: A B CItem pulled from collection:  ASecond Iteration: B C

Page 32: Queue data structure

Clear a Queue using System;using System.Collections;

class MainClass{  static void Main(string[] args)  {    Queue a = new Queue(10);    int x = 0;

    a.Enqueue(x);    x++;    a.Enqueue(x);    foreach (int y in a)    {      Console.WriteLine(y);    }

    a.Dequeue();    a.Clear();  }}

01

Page 33: Queue data structure

Demonstrate the Queue class Demonstrate the Queue class

// Demonstrate the Queue class.  using System; using System.Collections;  public class QueueDemo {   static void showEnq(Queue q, int a) {     q.Enqueue(a);     Console.WriteLine("Enqueue(" + a + ")");      Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");      Console.WriteLine();           }  static void showDeq(Queue q) {     Console.Write("Dequeue -> ");     int a = (int) q.Dequeue();     Console.WriteLine(a);      Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " "); 

// Demonstrate the Queue class.  using System; using System.Collections;  public class QueueDemo {   static void showEnq(Queue q, int a) {     q.Enqueue(a);     Console.WriteLine("Enqueue(" + a + ")");      Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");      Console.WriteLine();           }  static void showDeq(Queue q) {     Console.Write("Dequeue -> ");     int a = (int) q.Dequeue();     Console.WriteLine(a);      Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " "); 

Page 34: Queue data structure

using System; using System.Collections; public class QueueDemo {   static void showEnq(Queue q, int a) {     q.Enqueue(a);     Console.WriteLine("Enqueue(" + a + ")");   Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");    Console.WriteLine();           }   static void showDeq(Queue q) {     Console.Write("Dequeue -> ");     int a = (int) q.Dequeue();     Console.WriteLine(a);     Console.Write("queue: ");     foreach(int i in q)       Console.Write(i + " ");      Console.WriteLine();           } 

   public static void Main() {     Queue q = new Queue();    foreach(int i in q)       Console.Write(i + " ");     Console.WriteLine();             showEnq(q, 22);     showEnq(q, 65);     showEnq(q, 91);     showDeq(q);     showDeq(q);     showDeq(q);     try {       showDeq(q);     } catch (InvalidOperationException) {       Console.WriteLine("Queue empty.");     }   } }