if 200 2016 struktur data - wordpress.com · if 200 2016 struktur data antrian & antrian dua...

33
IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni [email protected]

Upload: lykhanh

Post on 03-May-2019

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

IF 200 2016

Struktur DataAntrian & Antrian Dua Arah

(Queue & Deque)

Husni

[email protected]

Page 2: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Agenda & Reading

•Agenda • Introduction• Queue Abstract Data Type (ADT)• Implementing a queue using a list• Using the Queue ADT to solve problems• A Circular Queue• The Deque Abstract Data Type

•Reading• Textbook: Problem Solving with Algorithms and Data

Structures• Chapter 3

2

Page 3: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

What is a Queue?

•Queues are appropriate for many real-world situations• Example: A line to buy a movie ticket

• Computer applications, e.g. a request to print a document

•A queue is an ordered collection of items where the addition of new items happens at one end (the rear or back of the queue) and the removal of existing items always takes place at the other end (the front of the queue).• New items enter at the back, or rear, of the queue

• Items leave from the front of the queue

• First-in, first-out (FIFO) property: • The first item inserted into a queue is the first item to leave

3

Page 4: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

More formally…

• Queues implement the FIFO (first-in first-out) policy: e.g. the printer / job queue!

4

enqueue( o )

is_empty()

peek()

dequeue()

front Rear of the

queue

Page 5: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

ADT Queue Operations

•What are the operations which can be used with a Queue Abstract Data?•Create an empty queue: •Determine whether a queue is empty: •Add a new item to the queue: enqueue

•Remove from the queue the item that was added earliest: dequeue

•Retrieve from the queue the item that was added earliest: peek

5

Page 6: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

The Queue Abstract Data Type

•Queue() creates a new queue that is empty. • It needs no parameters and returns an empty queue.

•enqueue(item) adds a new item to the rear of the queue. • It needs the item and returns nothing.

•dequeue() removes the front item from the queue. • It needs no parameters and returns the item. The queue

is modified.

• is_empty() tests to see whether the queue is empty. • It needs no parameters and returns a boolean value.

• size() returns the number of items in the queue. • It needs no parameters and returns an integer.

6

Page 7: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Queue Implementation In Python•We use a python List data structure to implement the

queue.• Remember:

• the addition of new items takes place at the beginning of the list • the removal of existing items takes place at the end of the list

7

class Queue:

def __init__(self):

self.items = []

def is_empty(self):

return self.items == []

def size(self):

return len(self.items)

def enqueue(self, item):

self.items.insert(0,item)

def dequeue(self):

return self.items.pop()

Enqueue

(rear of the

queue)

Dequeue

(front of

the queue)

Page 8: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Code Example – Result

• Queue operations, state of the queue, values returned

8

q.is_empty()

q.enqueue(4)

q.enqueue('dog')

q.enqueue(True)

q.size()

q.is_empty()

q.enqueue(8.4)

q.dequeue()

q.dequeue()

q.size()

[]

[4]

['dog',4]

[True,'dog',4]

[True,'dog',4]

[True,'dog',4]

[8.4,True,'dog',4]

[8.4,True,'dog']

[8.4,True]

[8.4,True]

True

3

False

4

'dog'

2

q = Queue()Enqueue:

(rear of the queue)

(beginning of the list)

Page 9: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Example Applications

•Simulation: Hot Potato

•Simulation: Printing Tasks

9

Page 10: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

1. Simulation: Hot Potato

•Six person game of Hot Potato•Children form a circle and pass an item from

neighbour to neighbour as fast as they can. At a certain point in the game, the action is stoppedand the child who has the item (the potato) is removed from the circle. Play continues until only one child is left.

10

Page 11: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

1. Simulation: Hot Potato

• Simulation of Hot Potato

• 1st round:• 2nd round:

• 3rd round:• Finally

11

hotPotato([Bill, David, Susan, Jane], 3) Jane Susan David Bill

Bill Jane Susan David

Enqueue

(rear of the queue)dequeue

David Bill Jane Susan

0

1

2 Susan David Bill Jane

Remove

Jane

Bill Susan David

David Bill Susan

0

1

2 Susan David Bill

Remove

Bill

David Susan

Susan David

0

1

2 David Susan Remove

SusanDavid

Page 12: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Hot Potato- Code

12

def hotPotato(namelist, num):simqueue = Queue()for name in namelist:

simqueue.enqueue(name)

while simqueue.size() > 1:for i in range(num):

simqueue.enqueue(simqueue.dequeue())

simqueue.dequeue()

return simqueue.dequeue()

Return the name when there is only

ONE name remains in the queue

Move element from the front

of the queue to the end

Page 13: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Simulation

•Simulation: a technique for modelling the behaviour of both natural and human-made systems

•Goal• Generate statistics summarising the performance of an

existing system• Predict the performance of a proposed system

•An example: Behaviour of a printing tasks – how to optimise? • Reduce number of complaints from our students about how

long they have to wait for service from a shared printer• Before hiring a faster printer: evaluate the approximate

average time that a student has to wait• To spend a few days and measure with a stopwatch: not an

exciting prospect! 13

Page 14: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

2. Printing Tasks• Students send printing tasks to the shared printer, the tasks are

placed in a queue to be processed in a first-come first-served manner. • Is the printer capable of handling a certain amount of work?

• The slower printing speed could make students wait too long. What page rate should be used?

• => Build a simulation that models the laboratory:• Students submit printing tasks, we will add them to a waiting list, a queue of

print tasks attached to the printer.

• When the printer completes a task, it will look at the queue to see if there are any remaining tasks to process.

14

enqueue

Page 15: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Simulation

•How to determine when certain events occur?•By studying the real world, mathematicians have

learned to model events such as the arrival of tasks using techniques from probability theory

•This statistical information is incorporated into the math model of the system and is used to generate events reflecting the real world.

•A time-driven simulation•Simulated time is advanced by a single time unit•The time of an event, such as an arrival or

departure, is determined randomly and compared with a simulated clock

15

Page 16: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

2. Printing Tasks – An Example

•Simulation for a period of 1200 seconds• Rate: 5 pages per minute• 6 printing tasks have been added to the queue. • Average waiting time is 26 sec.

16

Task At (currentsecond)

Number of pages

Timelength

1 190 1 12

2 656 18 216

3 778 8 96

4 906 9 108

5 1136 2 24

6 1193 30 240

Page 17: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

An Example

17

Printing T1

Printing

Queue

T3

new

task

190

202

656

778

872906968

1076

1136

11601193

Printing T2

Printing T3T4

Printing T4

Printing T5

Printing T6

from To description

190 Task 1 created (12 sec)Added to the printing queue

190 202 Removed T1 from the queuePrinting Task 1

202 Task1 finished

656 Task 2 created (216 sec)Added to the printing queue

656 872 Removed T2 from the queuePrinting Task 2

778 Task 3 created (96 sec)Added to the printing queue

872 968 Removed T3 from the queuePrinting Task 3

906 Task 4 created (108 sec)Added to the printing queue

968 1076 Removed T4 from the queuePrinting Task 4

1136 Task 5 created (24 sec)Added to the printing queue

1136 1160 Removed T5 from the queuePrinting Task 5

1193 Task 6 created (240 sec)Added to the printing queue

1193 1433 Removed T6 from the queuePrinting Task 6

Waiting time:

872-778 = 94

968-906 = 62

Page 18: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue

• What is the Big-O performance of enqueue and dequeue of the implementation using Python List?

•enqueue(…): O(n)• Shifting array elements to the right after each addition – too

Expensive!

•dequeue() : O(1)

• Another Implementation: Circular Queue

•enqueue & dequeue : O(1)• Items can be added/removed without shifting the other items in

the process

18

def enqueue(self, item):

self.items.insert(0,item)

def dequeue(self):

return self.items.pop()

Viewed as a circle

instead of line

Page 19: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue: Set up

•Uses a Python list data structure to store the items in the queue.

•The list has an initial capacity (all elements None) •Keeps an index of the current front of the queue and

of the current back of the queue. • set front to 0, • set back to MAX_QUEUE – 1, • set count to 0

•New items are enqueued at the back index position• Items are dequeued at the front index position. •A count of the queue items to detect queue-full and

queue-empty conditions

19

To initialize the

queue

Page 20: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue: How To Advance• Queue-empty:

• front is one slot ahead of back

• When either front or back advances past MAX_QUEUE - 1, it wraps around to 0• The wrap-around effect: by using Modulus (%) arithmetic operator

• enqueue• If it is not full,

• dequeue• If it is not empty

20

self.back = (self.back + 1) % self.MAX_QUEUE

self.items[self.back] = item

self.count += 1

item = self.items[self.front]

self.front = (self.front + 1) % self.MAX_QUEUE

self.count -= 1

return item

Page 21: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue: enqueue(32)

• Before:

• After:

• New item is inserted at the position following back• back is advanced by one position• count is incremented by 1

21

self.back = (self.back + 1) % self.MAX_QUEUE

self.items[self.back] = item

self.count += 1

enqueue

Page 22: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue: dequeue()

• Before:

• After:

• Value in front position is removed and returned

• front is advanced by 1

• count is decremented by 122

item = self.items[self.front]

self.front = (self.front + 1) % self.MAX_QUEUE

self.count -= 1

return item

Two spaces left!dequeue

Page 23: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue: enqueue(8) & enqueue(50)

• Before:

• After:

• After running the first enqueue, back = 6• After running the second enqueue, back = 0

• as the “Back” is wrapped around the list23

Two spaces left!enqueue

Page 24: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue: Empty ? Full?

• front and back cannot be used to distinguish between queue-full and queue-empty conditions for a circular array

• Case 1:

24

q = Queuecircular(8)

q.enqueue(5)

q.enqueue(2)

q.enqueue(1)

q.enqueue(7)

q.enqueue(9)

q.dequeue()

q.dequeue()

q.dequeue()

q.dequeue()

52

q.dequeue()

front = 5

back = 4

Page 25: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Circular Queue: Empty ? Full?

• Case 2:

• is_empty()

• is_full()

25

...

q.enqueue(2)

q.enqueue(4)

q.enqueue(1)

q.enqueue(7)

q.enqueue(6)

q.enqueue(3)

q.enqueue(8)

q.enqueue(9) front = 5

back = 4

(Same as before)!

return self.count == 0

return self.MAX_QUEUE <= self.count

Page 26: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Deque : Abstract Data Type

•Deque - Double Ended Queue•A deque is an ordered collection of items where items are added and removed from either end, either front or back.

•The newest item is at one of the ends

26

Page 27: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

ADT Deque Operations

•What are the operations which can be used with a Deque Abstract Data?•Create an empty deque: •Determine whether a deque is empty: •Add a new item to the deque:

•add_front()

•add_rear()

•Remove from the deque the item that was added earliest:

• remove_front()

• remove_rear() 27

Page 28: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Deque In Python

•We use a python List data structure to implement the deque.

28

class Deque:

def __init__(self):

self.items = []

...

def add_front(self, item):

self.items.append(item)

def add_rear(self, item):

self.items.insert(0,item)

def remove_front(self):

return self.items.pop()

def remove_rear(self):

return self.items.pop(0)

(rear of the

deque)

(front of

the deque)

Page 29: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Deque: Code Example – Result

• Deque operations, state of the deque, values returned

29

d = Deque()

d.is_empty()

d.add_rear(4)

d.add_rear('dog')

d.add_front('cat')

d.add_front(True)

d.size()

d.is_empty()

d.add_rear(8.4)

d.remove_rear()

d.remove_front()

[]

[4]

['dog',4,]

['dog',4,'cat']

['dog',4,'cat',True]

['dog',4,'cat',True]

['dog',4,'cat',True]

[8.4,'dog',4,'cat',True]

['dog',4,'cat',True]

['dog',4,'cat']

True

4

False

8.4

True

(rear of the

deque)

(front of

the deque)

Page 30: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Deque: Big-O Performance

• O(1)

• add_front() • remove_front()

• O(n)

• add_rear() • remove_rear()

30

def add_front(self, item):

self.items.append(item)

def add_rear(self, item):

self.items.insert(0,item)

def remove_front(self):

return self.items.pop()

def remove_rear(self):

return self.items.pop(0)

(rear of the

deque)

(front of

the deque)

Page 31: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Deque Application: Palindrome Checker

•A string which reads the same either left to right, or right to left is known as a palindrome• radar•deed•A dog, a plan, a canal: pagoda.

31

Page 32: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Palindrome Checker - Algorithm

•Create a deque to store the characters of the string• The front of the deque will hold the first character of the

string and the rear of the deque will hold the lastcharacter

•Remove both of them directly, we can compare them and continue only if they match. • If we can keep matching first and the last items, we will

eventually either run out of characters or be left with a deque of size 1 • In either case, the string must be a palindrome.

32

Page 33: IF 200 2016 Struktur Data - WordPress.com · IF 200 2016 Struktur Data Antrian & Antrian Dua Arah (Queue & Deque) Husni Husni@trunojoyo.ac.id

Summary

•The definition of the queue operations gives the ADT queue first-in, first-out (FIFO) behaviour

•To distinguish between the queue-full and queue-empty conditions in a queue implementation that uses a circular array, • count the number of items in the queue

•Models of real-world systems often use queues

33