Top Banner
Data Structures & Algorithms Lecture 2d: Queue Data Lecture 2d: Queue Data Structures Structures Joan Wakasa Murumba Joan Wakasa Murumba
38
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: Lecture 2d queues

Data Structures & Algorithms

Lecture 2d: Queue Data StructuresLecture 2d: Queue Data Structures

Joan Wakasa MurumbaJoan Wakasa Murumba

Page 2: Lecture 2d queues

Queue ADT

Like a stack, aLike a stack, a queue queue is also a list. is also a list. However, with a queue, insertion is done at However, with a queue, insertion is done at

one end, while deletion is performed at the one end, while deletion is performed at the other end.other end.

Accessing the elements of queues follows a Accessing the elements of queues follows a First In, First Out (FIFO) order.First In, First Out (FIFO) order. Like customers standing in a check-out Like customers standing in a check-out

line in a store, the first customer in is the line in a store, the first customer in is the first customer served.first customer served.

Page 3: Lecture 2d queues

The Queue ADT

Another form of restricted listAnother form of restricted list Insertion is done at one end, whereas Insertion is done at one end, whereas

deletion is performed at the other enddeletion is performed at the other end Basic operations:Basic operations:

EnqueueEnqueue DequeueDequeue

First-in First-out (FIFO) listFirst-in First-out (FIFO) list

Page 4: Lecture 2d queues

Queue

Page 5: Lecture 2d queues

Enqueue and Dequeue

Primary queue operations: Enqueue and Primary queue operations: Enqueue and DequeueDequeue

Like check-out lines in a store, a queue has a Like check-out lines in a store, a queue has a front and a rear. front and a rear.

EnqueueEnqueue Insert an element at the rear of the queueInsert an element at the rear of the queue

DequeueDequeue Remove/delete an element from the front of Remove/delete an element from the front of

the queuethe queue

Page 6: Lecture 2d queues

Enqueue and Dequeue

Insert (Enqueue)

Remove(Dequeue)

rearfront

Page 7: Lecture 2d queues

The Queue Operations

A queue is like a line of people A queue is like a line of people waiting for a bank teller. The queue waiting for a bank teller. The queue has a has a frontfront and a and a rearrear..

$ $

FrontRear

Page 8: Lecture 2d queues

The Queue Operations

New people must enter the queue at the rear. New people must enter the queue at the rear. The C++ queue class calls this a The C++ queue class calls this a pushpush, although it , although it

is usually called an is usually called an enqueueenqueue operation. operation.

$ $

FrontRear

Page 9: Lecture 2d queues

The Queue Operations

When an item is taken from the queue, it When an item is taken from the queue, it always comes from the front. The C++ always comes from the front. The C++ queue calls this a queue calls this a poppop, although it is usually , although it is usually called a called a dequeuedequeue operation. operation.

$ $

FrontRear

Page 10: Lecture 2d queues

Array Implementation of Queue

When enqueuing, the When enqueuing, the front indexfront index is always fixed is always fixed and the and the rear indexrear index moves forward in the array. moves forward in the array.

There are several different algorithms to There are several different algorithms to implement Enqueue and Dequeueimplement Enqueue and Dequeue

front

rear

Enqueue(3)

3

front

rear

Enqueue(6)

3 6

front

rear

Enqueue(9)

3 6 9

Page 11: Lecture 2d queues

Queue Implementation of Array

When enqueuing, the When enqueuing, the front indexfront index is always fixed is always fixed and the and the rear indexrear index moves forward in the array. moves forward in the array.

When dequeuing, the element at the front of the When dequeuing, the element at the front of the queue is removed. Move all the elements after it queue is removed. Move all the elements after it by one position. (Inefficient!!!)by one position. (Inefficient!!!)

Dequeue()

front

rear

6 9

Dequeue() Dequeue()

front

rear

9

rear = -1

front

Page 12: Lecture 2d queues

Queue Implementation of Array

Better wayBetter way When an item is enqueued, make the When an item is enqueued, make the rear rear

indexindex move forward. move forward. When an item is dequeued, the When an item is dequeued, the front indexfront index

moves by one element towards the back of moves by one element towards the back of the queue (thus removing the front item, so the queue (thus removing the front item, so no copying to neighboring elements is no copying to neighboring elements is needed).needed).

Page 13: Lecture 2d queues

Array Implementation....

A queue can be implemented with an array. A queue can be implemented with an array. For example, this queue contains the integers For example, this queue contains the integers 4 (at the front), 8 and 6 (at the rear).4 (at the front), 8 and 6 (at the rear).

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

An array of integers to An array of integers to implement a queue of implement a queue of integersintegers

4 8 6

Page 14: Lecture 2d queues

Array Implementation....

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

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

4 8 6

sizesize3

firstfirst0

lastlast2

Page 15: Lecture 2d queues

A Dequeue Operation....

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

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

4 8 6

sizesize2

firstfirst1

lastlast2

Page 16: Lecture 2d queues

An Enqueue Operation....

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

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

28 6

sizesize3

firstfirst1

lastlast3

Page 17: Lecture 2d queues

At the End of the Array...

There is special behaviour at the There is special behaviour at the end of the array. end of the array.

For example, suppose we want to For example, suppose we want to add a new element to this queue, add a new element to this queue, where the last index is [5]:where the last index is [5]:

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

2 16

sizesize3

firstfirst3

lastlast5

Page 18: Lecture 2d queues

At the End of the Array...

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

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

2 16

sizesize4

firstfirst3

lastlast0

4

Page 19: Lecture 2d queues

19

..Array implementation of queues

A queue is a first in, first out (FIFO) data structureA queue is a first in, first out (FIFO) data structure This is accomplished by inserting at one end (the This is accomplished by inserting at one end (the

rear) and deleting from the other (the front)rear) and deleting from the other (the front)

To insert:To insert: put new element in location 4, and put new element in location 4, and set rear to 4set rear to 4

To delete:To delete: take element from location 0, and set take element from location 0, and set front to 1 front to 1

17 23 97 44

0 1 2 3 4 5 6 7

myQueue:

rear = 3front = 0

Page 20: Lecture 2d queues

20

…Array implementation of queues

Notice how the array contents “crawl” to the right as elements are Notice how the array contents “crawl” to the right as elements are inserted and deletedinserted and deleted

This will be a problem after a while!This will be a problem after a while!

17 23 97 44 333After insertion:

23 97 44 333After deletion:

rear = 4front = 1

17 23 97 44Initial queue:

rear = 3front = 0

Page 21: Lecture 2d queues

Circular Arrays

We can treat the array holding the queue We can treat the array holding the queue elements as circular (joined at the ends)elements as circular (joined at the ends)

44 55 11 22 33

0 1 2 3 4 5 6 7

myQueue:

rear = 1 front = 5

Elements were added to this queue in the order 11, Elements were added to this queue in the order 11, 22, 33, 44, 55, and will be removed in the same order22, 33, 44, 55, and will be removed in the same order

Use: front = (front + 1) % myQueue.length;Use: front = (front + 1) % myQueue.length;and: rear = (rear + 1) % myQueue.length;and: rear = (rear + 1) % myQueue.length;

Page 22: Lecture 2d queues

…Full and empty queues

If the queue were to become completely full, it would If the queue were to become completely full, it would look like this:look like this:

If we were then to remove all eight elements, making If we were then to remove all eight elements, making the queue completely empty, it would look like this:the queue completely empty, it would look like this:

44 55 66 77 88 11 22 33

0 1 2 3 4 5 6 7myQueue:

rear = 4 front = 5

0 1 2 3 4 5 6 7

myQueue:

rear = 4 front = 5This is a problem!

Page 23: Lecture 2d queues

Full and empty queues: solutions Solution #1:Solution #1: Keep an additional variable Keep an additional variable

Solution #2:Solution #2: (Slightly more efficient) Keep a gap between (Slightly more efficient) Keep a gap between elements: consider the queue full when it has n-1 elementselements: consider the queue full when it has n-1 elements

44 55 66 77 88 11 22 33

0 1 2 3 4 5 6 7

myQueue:

rear = 4 front = 5count = 8

44 55 66 77 11 22 33

0 1 2 3 4 5 6 7

myQueue:

rear = 3 front = 5

Page 24: Lecture 2d queues

Advantages of Array Implementation of a Queue

Easy to implementEasy to implement But it has a limited capacity with a fixed arrayBut it has a limited capacity with a fixed array Or you must use a dynamic array for an Or you must use a dynamic array for an

unbounded capacityunbounded capacity

Page 25: Lecture 2d queues

Queue Class

IsFull: return true if queue is full, return IsFull: return true if queue is full, return false otherwisefalse otherwise

Enqueue: add an element to the rear of Enqueue: add an element to the rear of queuequeue

Dequeue: delete the element at the front Dequeue: delete the element at the front of queueof queue

DisplayQueue: print all the dataDisplayQueue: print all the data

Page 26: Lecture 2d queues

Linked List Implementation

10

15

7

null

13

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

head_ptrtail_ptr

Page 27: Lecture 2d queues

Linked List Implementation

10

15

7

null

13

Which end do you think is the Which end do you think is the front of the queue? Why?front of the queue? Why?

head_ptrtail_ptr

Page 28: Lecture 2d queues

Linked List Implementation

10

15

7

nullhead_ptr

13

The head_ptr points to the front The head_ptr points to the front of the list.of the list.

Because it is harder to remove Because it is harder to remove items from the tail of the list.items from the tail of the list.

tail_ptr

Front

Rear

Page 29: Lecture 2d queues

29

Enqueueing a node

17

Node to be enqueued

To Enqueue (add) a node: Find the current last node Change it to point to the new last node Change the last pointer in the list header

2344

lastfirst

97

Page 30: Lecture 2d queues

30

Enqueueing a node

17

Node to be enqueued

To enqueue (add) a node:Find the current last nodeChange it to point to the new last nodeChange the last pointer in the list header

2344

lastfirst

97

Page 31: Lecture 2d queues

31

Dequeueing a node

To dequeue (remove) a node:To dequeue (remove) a node: Copy the pointer from the first node into Copy the pointer from the first node into

the headerthe header

44 97 23 17

lastfirst

Page 32: Lecture 2d queues

Queue Class

Attributes of QueueAttributes of Queue front/rear: front/rear indexfront/rear: front/rear index counter: number of elements in the queuecounter: number of elements in the queue maxSize: capacity of the queuemaxSize: capacity of the queue values: point to an array which stores values: point to an array which stores

elements of the queueelements of the queue Operations of QueueOperations of Queue

IsEmpty: return true if queue is empty, IsEmpty: return true if queue is empty, return false otherwisereturn false otherwise

Page 33: Lecture 2d queues

Queue operations

add(Object item)add(Object item) a.k.a. enqueue(Object item)a.k.a. enqueue(Object item)

Object get()Object get() a.k.a. Object front()a.k.a. Object front()

Object remove()Object remove() a.k.a. Object dequeue()a.k.a. Object dequeue()

boolean isEmpty()boolean isEmpty() Specify in an interface, allow varied Specify in an interface, allow varied

implementationsimplementations

Page 34: Lecture 2d queues

34

Queue implementation details

With an array implementation:With an array implementation: You can have both overflow and underflowYou can have both overflow and underflow You should set deleted elements to nullYou should set deleted elements to null

With a linked-list implementation:With a linked-list implementation: You can have underflowYou can have underflow Overflow is a global out-of-memory conditionOverflow is a global out-of-memory condition There is no reason to set deleted elements to nullThere is no reason to set deleted elements to null

Page 35: Lecture 2d queues

35

Applications of Queues

Direct applicationsDirect applications Waiting lists, bureaucracyWaiting lists, bureaucracy Access to shared resources (e.g., Access to shared resources (e.g.,

printer)printer) MultiprogrammingMultiprogramming

Indirect applicationsIndirect applications Auxiliary data structure for algorithmsAuxiliary data structure for algorithms Component of other data structuresComponent of other data structures

Page 36: Lecture 2d queues

36

Application: Round Robin Schedulers

We can implement a round robin scheduler using a We can implement a round robin scheduler using a queue, queue, QQ, by repeatedly performing the following , by repeatedly performing the following steps:steps:

1.1. e = Q.e = Q.dequeue()dequeue()

2.2. Service element Service element ee

3.3. Q.Q.enqueue(enqueue(ee))

The Queue

Shared Service

1. Dequeue the next element

3. Enqueue the serviced element

2 . Service the next element

Page 37: Lecture 2d queues

37

Priority Queue ImplementationSequence-based Priority Queue

Implementation with an Implementation with an unsorted listunsorted list

Performance:Performance: insert takes insert takes OO(1) time (1) time

since we can insert the since we can insert the item at the beginning or item at the beginning or end of the sequenceend of the sequence

removeMin and min take removeMin and min take OO((nn) time since we have ) time since we have to traverse the entire to traverse the entire sequence to find the sequence to find the smallest smallest key key

Implementation with a Implementation with a sorted listsorted list

Performance:Performance: insert takes insert takes OO((nn) time ) time

since we have to find the since we have to find the place where to insert the place where to insert the itemitem

removeMin and min take removeMin and min take OO(1) time, since the (1) time, since the smallest key is at the smallest key is at the beginningbeginning

4 5 2 3 1 1 2 3 4 5

Page 38: Lecture 2d queues

38

Priority Queue Applications

Priority-based OS process schedulerPriority-based OS process scheduler