Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential...

24
Data Structures for Data Structures for Media Media Queues Queues

Transcript of Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential...

Page 1: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Data Structures for MediaData Structures for MediaQueuesQueues

Page 2: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Queue Abstract Data TypeQueue Abstract Data Type Sequential AllocationSequential Allocation Linked AllocationLinked Allocation ApplicationsApplications Priority QueuesPriority Queues

OutlineOutline

Page 3: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Queue is a list with the restriction that Queue is a list with the restriction that insertions are performed insertions are performed at one endat one end and and deletions are performed deletions are performed at the other endat the other end of the listof the list

Also known as: First-in-first-out (FIFO) listAlso known as: First-in-first-out (FIFO) list

QueueQueue

Page 4: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Value:Value: A sequence of items that belong to some data type ITEM_TYPEA sequence of items that belong to some data type ITEM_TYPE

Operations on q:Operations on q:1. Boolean IsEmpty()1. Boolean IsEmpty()Postcondition: If the queue is empty, return true, otherwise return falsePostcondition: If the queue is empty, return true, otherwise return false2. Boolean IsFull()2. Boolean IsFull()Postcondition: If the queue is full, return true, otherwise return falsePostcondition: If the queue is full, return true, otherwise return false3. ITEM_TYPE Dequeue() 3. ITEM_TYPE Dequeue() /*take out the front one and return its value*//*take out the front one and return its value*/Precondition: q is not emptyPrecondition: q is not emptyPostcondition: The front item in q is removed from the sequence and returnPostcondition: The front item in q is removed from the sequence and return

eded4. Void Enqueue(ITEM_TYPE e) 4. Void Enqueue(ITEM_TYPE e) /*to append one item to the rear of the queue*/*to append one item to the rear of the queue*

//Precondition: q is not ______Precondition: q is not ______Postcondition: e is added to the sequence as the rear onePostcondition: e is added to the sequence as the rear one

ADT of QueueADT of Queue

Page 5: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Implementation of QueueImplementation of QueueSequential Allocation (Using Array)Sequential Allocation (Using Array)

#define TOTAL_SLOTS 100__gc class MyQueue

{

private:

int front;

int rear;

int items[TOTAL_SLOTS];

};

Slot#0 Slot#1 Slot#2 … Slot#98 Slot#99

Slot#0Item A

Slot#1Item B

Slot#2Item C

Slot#3Empty

… Empty

Slot#99 Empty

Suppose some items are appended into the queue:

//the index of the front slot that contains the front item

//the index of the first empty slot at the rear of queue

front rear

Page 6: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

#define TOTAL_SLOTS 100__gc class MyQueue{ private: int front; int rear; int items[TOTAL_SLOTS];};

Slot#0Item A

Slot#1Item B

Slot#2Item C

Slot#3Empty

… Empty

Slot#99 Empty

front rear

If the queue is empty, we’ll have___________.

Suppose we remove 2 items:

Slot#0Empty

Slot#1Empty

Slot#2Item C

Slot#3Empty

… Empty

Slot#99 Empty

front rear

Then we remove the remaining one item:

Slot#0Empty

Slot#1Empty

Slot#2Empty

Slot#3Empty

… Empty

Slot#99 Empty

rearfront

Implementation of QueueImplementation of QueueSequential Allocation (Using Array)Sequential Allocation (Using Array)

Page 7: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Suppose 2 items are removed and 96 items added:

front rear

Slot#0Empty

Slot#1Empty

Slot#2Item C

Slot#3Item D

Slot#4 Item E

… Slot#98Item XX

Slot#99Empty

Then, we add (append) item YY:

frontrear

Slot#0Empty

Slot#1Empty

Slot#2Item C

Slot#3Item D

Slot#4 Item E

… Slot#98Item XX

Slot#99Item YY

Then, we add (append) one more item ZZ:

frontrear

Slot#0Item ZZ

Slot#1Empty

Slot#2Item C

Slot#3Item D

Slot#4 Item E

… Slot#98Item XX

Slot#99Item YY

However, we can’t add further item. Reason: we should not let rear = front if the queue is not empty. (The queue is empty when rear = front)

Hence, this implementation allows only “______________________” items.

Slot#0Item A

Slot#1Item B

Slot#2Item C

Slot#3Empty

… Empty

Slot#99 Empty

front rear

#define TOTAL_SLOTS 100__gc class MyQueue{ private: int front; int rear; int items[TOTAL_SLOTS];};

Page 8: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Implementation of QueueImplementation of QueueSequential Allocation (Using Array)Sequential Allocation (Using Array)

#define TOTAL_SLOTS 100__gc class MyQueue

{

private:

int front;

int rear;

int items[TOTAL_SLOTS];

public: bool isEmpty();

bool isFull();

enqueue(int );

int dequeue();

};

//the index of the front slot that contains the front item

//the index of the first empty slot at the rear of queue

Page 9: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Implementation of QueueImplementation of QueueSequential Allocation (Using Array)Sequential Allocation (Using Array)

bool MyQueue::isEmpty(){

return (front==rear);}bool MyQueue::isFull(){

return((rear+1)%TOTAL_SLOTS==front);}

void MyQueue::enqueue(int data){

if(!isFull()){

items[rear]=data;rear=(rear+1)

}}

int MyQueue::dequeue( ){

int ret_val;if(!isEmpty()){

ret_val=items[front];front=(front+1)%TOTAL_SLOTS;return ret_val;

}}

%TOTAL_SLOTS;

Page 10: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

NULL

Implementation of QueueImplementation of QueueUsing Linked ListUsing Linked List

front rear

Queue can also be implemented with linked list.

A pointer front points to the first node of the queue.

A pointer rear points to the last node of the queue.

If the queue is empty, then front=rear=NULL.

When will the queue be full?

Page 11: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Linked Implementation of QueueLinked Implementation of Queue// MyQueue.h// MyQueue.h#pragma once#pragma once#include “stdlib.h”#include “stdlib.h”#using <mscorlib.dll>#using <mscorlib.dll>using namespaces System;using namespaces System;namespace LinkedListLibrarynamespace LinkedListLibrary{{

public __gc class MyQueuepublic __gc class MyQueue{{

public:public:MyQueue( );MyQueue( );

bool IsEmpty();bool IsEmpty();void Enqueue(int );void Enqueue(int );int Dequeue();int Dequeue();

private:private:ListNode* front;ListNode* front;ListNode* rear;ListNode* rear;int size;int size;

};};}}

// MyQueue.cpp// MyQueue.cpp

#include “MyQueue.h”#include “MyQueue.h”MyQueue::MyQueue()MyQueue::MyQueue(){{

size=0;size=0;front=NULL;front=NULL;rear=NULL;rear=NULL;

}}bool MyStack::IsEmpty()bool MyStack::IsEmpty(){{

return (front==NULL);return (front==NULL);}}

Page 12: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

To insert an item (Enqueue)To insert an item (Enqueue)We have We have 2 cases2 cases: :

The queue is empty or not.The queue is empty or not.

Step 1: Allocate a new slot, p, to store the item.

Step 2: Connect p to the queue (2 cases).

Step 3: Update the rear pointer to point to p.

Linked Implementation of QueLinked Implementation of Queueue

NULL

front rear

Item X

Item A

… New

front rear

Item X

Item A

… NewNULL

Case 2: The queue is not empty

Case 1: The queue is empty

NULL

rear

New

front

Newfront=NULL

rear=NULL

Page 13: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

To insert an item (Enqueue)To insert an item (Enqueue)We have We have 2 cases2 cases: :

The queue is empty or not.The queue is empty or not.

Step 1: Allocate a new slot, p, to store the item.

Step 2: Connect p to the queue (2 cases).

Step 3: Update the pRear pointer to point to p.

Linked Implementation of QueLinked Implementation of Queueue

// MyQueue.cpp// MyQueue.cpp

#include “MyQueue.h”#include “MyQueue.h”void MyQueue::Enqueue(int data)void MyQueue::Enqueue(int data){{

ListNode *p=new ListNode(data);ListNode *p=new ListNode(data);if (IsEmpty())if (IsEmpty())

front=p;front=p;elseelse

rear->next=p;rear->next=p;rear=p;rear=p;

}}

Page 14: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

To delete an item (the front item) and return itTo delete an item (the front item) and return itWe have We have 3 cases3 cases: :

The queue has 0 item, 1 item or more than one item.The queue has 0 item, 1 item or more than one item.

Linked Implementation of QueLinked Implementation of Queueue

Case 2: The queue has 1 item

Case 1: The queue has 0 item Output error

NULL

rear

Item A

front

front=NULL

rear=NULLCase 3: The queue has more than one

item

NULL

rear

Item A

front

front rear

Item XItem B … NULLItem A

Value of Item A

front rear

Item XItem B …Item A NULL

Value of Item A

Page 15: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

To delete an item (the front item) and return itTo delete an item (the front item) and return itWe have We have 3 cases3 cases: :

The queue has 0 item, 1 item or more than one item.The queue has 0 item, 1 item or more than one item.

Linked Implementation of QueLinked Implementation of Queueue

// MyQueue.cpp// MyQueue.cpp

#include “MyQueue.h”#include “MyQueue.h”int MyQueue::Dequeue()int MyQueue::Dequeue(){{

int ret_value;int ret_value;if (!IsEmpty())if (!IsEmpty()){{

ret_value=front->getData();ret_value=front->getData();front=front->next;front=front->next;if(front==NULL)if(front==NULL)

rear=NULL;rear=NULL;}}return ret_value;return ret_value;

}}

Page 16: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

In Game, when factory produce unitsIn Game, when factory produce units See online moviesSee online movies The way printer worksThe way printer works Round Robin Schedule Round Robin Schedule

Establish a queue for current jobsEstablish a queue for current jobs Whenever a time slot is used upWhenever a time slot is used up

Insert the current job into the queueInsert the current job into the queue Begin executing the job fetched from the Begin executing the job fetched from the

queuequeue

Application 1 Application 1 Phenomena on the computerPhenomena on the computer

Page 17: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

job job 11 : 4 time slots; job : 4 time slots; job 22 : 3 time slots : 3 time slots job job 33 : 1 time slot; job : 1 time slot; job 44 : 2 time slots : 2 time slots

Round Robin ScheduleRound Robin Schedule

1(4 left) 2(3 left) 3(1 left) 4(2 left)

2(3 left) 3(1 left) 4(2 left) 1(3 left)

3(1 left) 4(2 left) 1(3 left) 2(2 left)

4(2 left) 1(3 left) 2(2 left)

1(3 left) 2(2 left) 4(1 left)

2(2 left) 4(1 left) 1(2 left)

2(1left) 4(1 left) 1(2 left)

2(1left) 1(2 left)

2(1left) 1(1 left)

1(1 left)

Page 18: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Application 2 Application 2 Reversing a StackReversing a Stack

Reversing a stackReversing a stackStack *s;Stack *s;Queue *p; Queue *p; ……while(!s->IsEmpty())while(!s->IsEmpty()){{ x = s->pop();x = s->pop();

p->Enqueue(x);p->Enqueue(x);}}while (!p->IsEmpty())while (!p->IsEmpty()){{ x = p->Dequeue();x = p->Dequeue();

s->push(x);s->push(x);}}

DCBA

empty

ABCD

stack

D C B Aqueue

Pop from stack andinsert into a queue

Delete from queue andPush onto stack

Page 19: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

In Game, when factory produce unitsIn Game, when factory produce units Suppose a factory can produce the Suppose a factory can produce the

following three units:following three units: AttackerAttacker Defender Defender WorkerWorker

When you are giving commands, you do When you are giving commands, you do not have so many time to worry about not have so many time to worry about the order of production. It should be AI’s the order of production. It should be AI’s work to arrange that for youwork to arrange that for you

Queue enough?Queue enough?

Least important

Most important

Moderately important

Page 20: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Priority QueuePriority Queue The elements in a stack or a FIFO queue are ordered based on The elements in a stack or a FIFO queue are ordered based on

the sequence in which they have been inserted.the sequence in which they have been inserted. In a priority queue, the sequence in which elements are In a priority queue, the sequence in which elements are

removed is based on the priority of the elements.removed is based on the priority of the elements.

APriority=1

BPriority=2

CPriority=3

DPriority=3

Ordered Priority Queue

(highest priority) (lowest priority)

BPriority=2

CPriority=3

APriority=1

DPriority=3

Unordered Priority Queue

The first element to be removed.

Priority QueuePriority Queue

Page 21: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Priority Queue - Array ImplementationPriority Queue - Array Implementation To implement a priority queue using an array such that the elements are To implement a priority queue using an array such that the elements are ordereordere

dd based on the priority.based on the priority.

Time complexity of the operations :Time complexity of the operations :

(assume the sorting order is from highest priority to lowest)(assume the sorting order is from highest priority to lowest)

InsertionInsertion:: Find the location of insertion. Find the location of insertion. O(__)O(__)

Shift the elements after the location Shift the elements after the location O(__)O(__)

where where n n = number of elements in the qu= number of elements in the queueeue

Insert the element to the found location Insert the element to the found location O(__)O(__)

Altogether: Altogether: O(__)O(__)

DeletionDeletion:: The highest priority element is at the front, ie. Remove the front elThe highest priority element is at the front, ie. Remove the front element (Shift the remaining) takes ement (Shift the remaining) takes O(__) O(__) timetime

The efficiency of insertion is important

Priority QueuePriority Queue

Page 22: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Priority Queue - Array ImplementationPriority Queue - Array Implementation To implement a priority queue using an array such that elements are To implement a priority queue using an array such that elements are unorderedunordered. .

Time complexity of the operations :Time complexity of the operations :

InsertionInsertion:: Insert the element at the rear position. Insert the element at the rear position. O(1)O(1)

DeletionDeletion:: Find the highest priority element to be removed. Find the highest priority element to be removed. O(n)O(n)

Copy the value of the element to return it later. Copy the value of the element to return it later. O(1)O(1)

Shift the following elements so as to fill the hole. Shift the following elements so as to fill the hole. O(n)O(n)

or replace the hole with the rear element or replace the hole with the rear element O(1)O(1)

Altogether: Altogether: O(n)O(n) The efficiency of deletion is important

Consider that, on the average,

Ordered Priority Queue: since it is sorted, every insertion needs to search half the array for the insertion position, and half elements are to be shifted.

Unordered Priority Queue: every deletion needs to search all n elements to find the highest priority element to delete.

Priority QueuePriority Queue

Page 23: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Priority Queue - List ImplementationPriority Queue - List Implementation To implement a priority queue as an To implement a priority queue as an orderedordered list. list.

Time complexity of the operations :Time complexity of the operations :

(assume the sorting order is from highest priority to lowest)(assume the sorting order is from highest priority to lowest)

Insertion: Insertion: Find the location of insertion. Find the location of insertion. O(n)O(n)

No need to shift elements after the location.No need to shift elements after the location.

Link the element at the found location. Link the element at the found location. O(1)O(1)

Altogether: Altogether: O(n)O(n)

Deletion: Deletion: The highest priority element is at the front. The highest priority element is at the front.

ie. Remove the front element takes ie. Remove the front element takes O(1) O(1) timetime

The efficiency of insertion is important.

More efficient than array implementation.

Priority QueuePriority Queue

Page 24: Data Structures for Media Queues. Queue Abstract Data Type Queue Abstract Data Type Sequential Allocation Sequential Allocation Linked Allocation Linked.

Priority Queue - List ImplementationPriority Queue - List Implementation To implement a priority queue as an To implement a priority queue as an unorderedunordered list. list.

Time complexity of the operations :Time complexity of the operations :

Insertion: Insertion: Simply insert the item at the rear. Simply insert the item at the rear. O(1)O(1)

Deletion: Deletion: Traverse the entire list to find the maximum priority element. Traverse the entire list to find the maximum priority element. O(n)O(n)..

Copy the value of the element to return it later. Copy the value of the element to return it later. O(1)O(1)

No need to shift any element. No need to shift any element.

Delete the node. Delete the node. O(1)O(1)

Altogether: Altogether: O(n)O(n)The efficiency of

deletion is important

Ordered list vs Unordered list

<Comparison is similar to array implementations.>

Priority QueuePriority Queue

We will come back to this after we learned trees