Queues CSE POSTECH Queues l l l 2

  • Slides: 46
Download presentation
Queues CSE, POSTECH

Queues CSE, POSTECH

Queues l l l 2 Like a stack, special kind of linear list One

Queues l l l 2 Like a stack, special kind of linear list One end is called front Other end is called rear Additions (insertions or enqueue) are done at the rear only Removals (deletions or dequeue) are made from the front only

Bus Stop Queue Bus Stop front rear l rear Remove a person from the

Bus Stop Queue Bus Stop front rear l rear Remove a person from the queue

Bus Stop Queue Bus Stop front rear

Bus Stop Queue Bus Stop front rear

Bus Stop Queue Bus Stop front rear

Bus Stop Queue Bus Stop front rear

Bus Stop Queue Bus Stop front rear l l Add a person to the

Bus Stop Queue Bus Stop front rear l l Add a person to the queue A queue is a FIFO (First-In, First-Out) list.

Queue ADT Abstract. Data. Type queue { instances ordered list of elements; one end

Queue ADT Abstract. Data. Type queue { instances ordered list of elements; one end is the front; the other is the rear; operations empty(): Return true if queue is empty, return false otherwise size(): Return the number of elements in the queue front(): Return the front element of queue back(): Return the back (rear) element of queue pop(): Remove an element from the queue // dequeue push(x): Add element x to the queue // enqueue } It is also possible to represent Queues using 1. 2. 7 Array-based representation Linked representation

The Abstract Class queue template <class T> // Program 9. 1 class queue {

The Abstract Class queue template <class T> // Program 9. 1 class queue { public: virtual ~queue() {} virtual bool empty() const = 0; virtual int size() const = 0; virtual T& front() = 0; virtual T& back() = 0; virtual void pop() = 0; virtual void push(const T& the. Element) = 0; };

Array-based Representation of Queue l Using simple formula equation location(i) = i – 1

Array-based Representation of Queue l Using simple formula equation location(i) = i – 1 – – – 9 The first element is in queue[0], the second element is in queue[1], and so on Front always equals zero, back (rear) is the location of the last element, and the queue size is rear + 1 How much time does it need for pop()?

Derive from Array. Linear. List l When front is left end of list and

Derive from Array. Linear. List l When front is left end of list and rear is right end: – – – l 10 Queue. empty() Array. Linear. List. empty() O(1) x = Queue. front() Array. Linear. List. get(0) O(1) x = Queue. back() Array. Linear. List. get(length) O(1) Queue. push(x) Array. Linear. List. insert(length, x) O(1) Queue. pop() Array. Linear. List. erase(0) O(length) To perform every operation in O(1) time, we need a customized array representation

Array-based Representation of Queue l Using modified formula equation location(i) = location(1) + i

Array-based Representation of Queue l Using modified formula equation location(i) = location(1) + i - 1 – – 11 No need to shift the queue one position left each time an element is deleted from the queue Instead, each deletion causes front to move right by 1 Front = location(1), rear = location(last element), and empty queue has rear < front What do we do when rear = Maxsize – 1 and front > 0?

Array-based Representation of Queue l Shifting a queue To continue adding to the queue,

Array-based Representation of Queue l Shifting a queue To continue adding to the queue, we shift all elements to the left end of the queue – But shifting increases the worst-case add time from Q(1) to Q(n) Need a better method! – Shifting a Queue 12

Array-based Representation of Queue l Remedy in modified formula equation that can provide the

Array-based Representation of Queue l Remedy in modified formula equation that can provide the worst-case add and delete times in Q(1): location(i) = (location(1) + i – 1) % Maxsize This 13 is called a Circular Queue

Custom Array Queue l Use a 1 D array queue l Circular view of

Custom Array Queue l Use a 1 D array queue l Circular view of array 14

Custom Array Queue l 15 Possible configurations with three elements.

Custom Array Queue l 15 Possible configurations with three elements.

Custom Array Queue l Use integer variables ‘front’ and ‘rear’. – – ‘front’ is

Custom Array Queue l Use integer variables ‘front’ and ‘rear’. – – ‘front’ is one position counter-clockwise from first element ‘rear’ gives the position of last element rear 16 front

Custom Array Queue l Add an element – – 17 Move ‘rear’ one clockwise.

Custom Array Queue l Add an element – – 17 Move ‘rear’ one clockwise. Then put an element into queue[rear].

Custom Array Queue l Remove an element – – 18 Move front one clockwise.

Custom Array Queue l Remove an element – – 18 Move front one clockwise. Then extract from queue[front].

Custom Array Queue l Moving clockwise – – 19 rear++; if (rear == queue.

Custom Array Queue l Moving clockwise – – 19 rear++; if (rear == queue. length) rear = 0; rear = (rear + 1) % queue. length;

Custom Array Queue l Empty that queue rear front 20

Custom Array Queue l Empty that queue rear front 20

Custom Array Queue l Empty that queue rear front 21

Custom Array Queue l Empty that queue rear front 21

Custom Array Queue l Empty that queue – – – 22 When a series

Custom Array Queue l Empty that queue – – – 22 When a series of removals causes the queue to become empty, front = rear. When a queue is constructed, it is empty. So initialize front = rear = 0.

Custom Array Queue l A Full Tank Please rear 23 front

Custom Array Queue l A Full Tank Please rear 23 front

Custom Array Queue l A Full Tank Please rear front 24

Custom Array Queue l A Full Tank Please rear front 24

Custom Array Queue l A Full Tank Please – – l 25 When a

Custom Array Queue l A Full Tank Please – – l 25 When a series of adds causes the queue to become full, front = rear. So we cannot distinguish between a full queue and an empty queue. How to differentiate two cases: queue empty and queue full?

Custom Array Queue l Remedies – Don’t let the queue get full Ø –

Custom Array Queue l Remedies – Don’t let the queue get full Ø – When the addition of an element will cause the queue to be full, increase array size Define a boolean variable last. Operation. Is. Add Following each add operation set this variable to true. Ø Following each delete operation set this variable to false. Ø Queue is empty iff (front == rear) && !last. Opeartion. Is. Add Ø Queue is full iff (front == rear) && last. Operation. Is. Add Ø 26

Custom Array Queue l Remedies (cont’d) – Define a variable Num. Elements Following each

Custom Array Queue l Remedies (cont’d) – Define a variable Num. Elements Following each add operation, increment this variable Ø Following each delete operation, decrement this variable Ø Queue is empty iff (front == rear) && (!Num. Elements) Ø Queue is full iff (front == rear) && (Num. Elements) Ø l l 27 See Programs 9. 2, 9. 3, 9. 4 See Figure 9. 7 for doubling array queue length

Linked Representation of Queue Can represent a queue using a chain l Need two

Linked Representation of Queue Can represent a queue using a chain l Need two variables, front and rear, to keep track of the two ends of a queue l Two options: 1) assign head as front and tail as rear (see Fig 9. 8 (a)), or 2) assign head as rear and tail as front (see Fig 9. 8 (b)) Which option is better and why? See Figures 9. 9 and 9. 10 l 28

Linked Queue Representations Head Tail Head Figure 9. 8 Linked Queues 29

Linked Queue Representations Head Tail Head Figure 9. 8 Linked Queues 29

Add to & Delete from a Linked Queue l l l 30 What is

Add to & Delete from a Linked Queue l l l 30 What is the time complexity for Fig 9. 8 (a)? Θ(1) What is the time complexity for Fig 9. 8 (b)? Θ(1) What is the time complexity for Fig 9. 9 (a)? Θ(1) What is the time complexity for Fig 9. 9 (b)? Θ(n) So, which option is better? Option 1

Linked Representation of Queue l l 31 How can we implement a linked representation

Linked Representation of Queue l l 31 How can we implement a linked representation of queue? See Program 9. 5 for implementing the push and pop methods of linked. Queue

Derive From Extended. Chain last. Node first. Node NULL a front l c d

Derive From Extended. Chain last. Node first. Node NULL a front l c d e rear When front is left end of list and rear is right end: – – – 32 b – empty() extended. Chain: : empty() size() extended. Chain: : size() front() get (0) back() get. Last() … new method push(the. Element) push_back(the. Element) pop() erase(0)

Revisit of Stack Applications l Applications in which the stack cannot be replaced with

Revisit of Stack Applications l Applications in which the stack cannot be replaced with a queue – – l Parentheses matching Towers of Hanoi Switchbox routing Method invocation and return Application in which the stack may be replaced with a queue – – Railroad Car Rearrangement Rat in a maze

Application: Rearranging Railroad Cars l l Similar to problem of Section 8. 5. 3

Application: Rearranging Railroad Cars l l Similar to problem of Section 8. 5. 3 using stacks This time holding tracks lie between the input and output tracks with the following same conditions: – Moving a car from a holding track to the input track or from the output track to a holding track is forbidden These tracks operate in a FIFO manner can implement using queues l We reserve track Hk for moving cars from the input track to the output track. So the number of tracks available to hold cars is k-1. l 34

Rearranging Railroad Cars l When a car is to be moved to a holding

Rearranging Railroad Cars l When a car is to be moved to a holding track, use the following selection method: – – – l Move a car c to a holding track that contains only cars with a smaller label If multiple such tracks exist, select one with the largest label at its left end Otherwise, select an empty track (if one remains) What happens if no feasible holding track exists? rearranging railroad cars is NOT possible l 35 See Figure 9. 11 and read its description

Implementing Rearranging Railroad Cars l What should be changed in previous program (in Section

Implementing Rearranging Railroad Cars l What should be changed in previous program (in Section 8. 5. 3)? 1. 2. l What is the time complexity of rearrangement? l 36 Decrease the number of tracks (k) by 1 Change the type of track to array. Queue O(number. Of. Cars * k) See Programs 9. 6 and 9. 7

Application: Wire Routing l l l 37 Similar to Rat in a Maze problem

Application: Wire Routing l l l 37 Similar to Rat in a Maze problem in Section 8. 5. 6, but this time it has to find the shortest path between two points to minimize signal delay Used in designing electrical circuit boards Read the problem description on pg. 336 Figure 9. 12 Wire Routing Example

Wire Routing Algorithm The shortest path between grid positions a and b is found

Wire Routing Algorithm The shortest path between grid positions a and b is found in two passes 1. Distance-labeling pass (i. e. , labeling grids) 2. Path-identification pass (i. e. , finding the shortest path) 38

Wire Routing Algorithm 1. Labeling Grids: Starting from position a, label its reachable neighbors

Wire Routing Algorithm 1. Labeling Grids: Starting from position a, label its reachable neighbors 1. Next, the reachable neighbors of squares labeled 1 are labeled 2. This labeling process continues until we either reach b or have no more reachable squares. The shaded squares are blocked squares. Figure 9. 13 Wire Routing 39

Wire Routing Algorithm 2. Finding the shortest path: Starting from position b, move to

Wire Routing Algorithm 2. Finding the shortest path: Starting from position b, move to any one of its neighbors labeled one less than b’s label. Such a neighbor must exist as each grid’s label is one more than that of at least one of its neighbors. From here, we move to one of its neighbors whose label is one less, and so on until we reach a. Figure 9. 13 Wire Routing 40

Wire Routing Algorithm Exercise Consider the wire-routing grid of Figure 9. 13(a). You are

Wire Routing Algorithm Exercise Consider the wire-routing grid of Figure 9. 13(a). You are to route a wire between a=(1, 1) and b=(1, 6). Label all grid positions that are reached in the distance-labeling pass by their distance value. Then use the methodology of the path -identification pass to mark the shortest wire path. a 1 b 1 2 14 2 3 4 5 5 6 5 7 a 13 14 12 13 11 12 11 8 9 10 11 Is there only one shortest path? 41 b a b

Implementing Wire Routing Algorithm l l l 42 An m x m grid is

Implementing Wire Routing Algorithm l l l 42 An m x m grid is represented as a 2 -D array with a 0 representing an open position and a 1 representing a blocked position the grid is surrounded by a wall of 1 s the array offsets helps us move from a position to its neighbors A queue keeps track of labeled grid positions whose neighbors have yet to be labeled What is the time complexity of the algorithm? O(m 2) for labeling grids & O(length of the shortest path) for path construction Read Program 9. 8

Application: Image-Component Labeling l Background information: – – – l 43 A digitized image

Application: Image-Component Labeling l Background information: – – – l 43 A digitized image is an m x m matrix of pixels. In a binary image, each pixel is 0 or 1. A 0 pixel represents image background, while a 1 represents a point on an image component. Two pixels are adjacent if one is to the left, above, right, or below the other. Two component pixels that are adjacent are pixels of the same image component. Problem: Label the component pixels so two pixels get the same label iff they are pixels of the same image component.

Image-Component Labeling Example Figure 9. 14 Image-Component Labeling l l 44 The blank squares

Image-Component Labeling Example Figure 9. 14 Image-Component Labeling l l 44 The blank squares represent background pixels and 1 s represent component pixels Pixels (1, 3), (2, 3), and (2, 4) are from the same component

Image-Component Labeling Algorithm l l Idea: Similar to the wire-routing problem Steps: 1. 2.

Image-Component Labeling Algorithm l l Idea: Similar to the wire-routing problem Steps: 1. 2. 3. 4. l l 45 Scan pixels one by one (row-major search). When encounter a 1 pixel, give a unique component identifier. Find all neighbors by expanding from that pixel and give the unique identifier. Repeat for all pixels. See program 9. 9 What is the time complexity of Program 9. 9?

READING l l 46 Read 9. 5. 4 Machine Shop Simulation Read all of

READING l l 46 Read 9. 5. 4 Machine Shop Simulation Read all of Chapter 9