1 / 34

Queues

Queues. Queue Definition. Ordered list with property: All insertions take place at one end (tail) All deletions take place at other end (head) Queue: Q = (a 0 , a 1 , …, a n-1 ) a0 is the front element, a n-1 is the tail, and a i is behind a i-1 for all i, 1 <= i < n. Queue Definition.

mharis
Download Presentation

Queues

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Queues

  2. Queue Definition Ordered list with property: • All insertions take place at one end (tail) • All deletions take place at other end (head) Queue: Q = (a0, a1, …, an-1) a0 is the front element, an-1 is the tail, and ai is behind ai-1 for all i, 1 <= i < n

  3. Queue Definition Because of insertion and deletion properties, Queue is very similar to: Line at the grocery store Cars in traffic Network packets …. Also called first-in first out lists

  4. Queue Implementation Ideas Container type class for holding data Array versus Linked List? Who’s better? Head index pointer Position right before first element in queue Tail index pointer Position of last element in queue

  5. Array-Based Queue Definition template <class KeyType> class Queue { public: Queue(int MaxQueueSize = DefaultSize); ~Queue(); bool IsFull(); bool IsEmpty(); void Add(const KeyType& item); KeyType* Delete(KeyType& item); private: void QueueFull(); // error handling void QueueEmpty(); // error handling int head, tail; KeyType* queue; int MaxSize; };

  6. Queue Implementation Constructor: template <class KeyType> Queue<KeyType>::Queue(int MaxQueueSize): MaxSize(MaxQueueSize) { queue = new KeyType[MaxSize]; head = tail = -1; }

  7. Queue Implementation Destructor: template <class KeyType> Queue<KeyType>::~Queue() { delete [] queue; head = tail = -1; }

  8. Queue Implementation IsFull() and IsEmpty(): template <class KeyType> bool Queue<KeyType>::IsFull() { return (tail == (MaxSize-1)); } template <class KeyType> bool Queue<KeyType>::IsEmpty() { return (head == tail); }

  9. Queue Implementation Add() and Delete(): template <class KeyType> void Queue<KeyType>::Add (const KeyType& item) { if (IsFull()) {QueueFull(); return;} else { tail = tail + 1; queue[tail] = item; } } template <class KeyType> KeyType* Queue<KeyType>::Delete(KeyType& item) { if (IsEmpty()) {QueueEmpty(); return 0}; else { head = head + 1; item = queue[head]; return &item; } }

  10. Example: Job Scheduling OS has to manage how jobs (programs) are executed on the processor – 2 typical techniques: -Priority based: Some ordering over of jobs based on importance (Professor X’s jobs should be allowed to run first over Professor Y). -Queue based: Equal priority, schedule in first in first out order.

  11. Queue Based Job Processing MaxSize = 4

  12. Job Processing • When J4 enters the queue, rear is updated to 3. • When rear is 3 in a 4-entry queue, run out of space. • The array may not really be full though, if head is not -1. • Head can be > -1 if items have been removed from queue. Possible Solution: When rear = (maxSize – 1) attempt to shift data forwards into empty spaces and then do Add.

  13. Queue Shift private void shiftQueue(KeyType* queue, int & head, int & tail) { int difference = head – (-1); // head + 1 for (int j = head + 1; j < maxSize; j++) { queue[j-difference] = queue[j]; } head = -1; tail = tail – difference; }

  14. Queue Shift Worst Case For Queue Shift: Full Queue Alternating Delete and Add statements

  15. Worst Case Queue Shift • Worst Case: • Shift entire queue: Cost of O(n) • Do every time perform an add • Too expensive to be useful Worst case is not that unlikely, so this suggests finding an alternative implementation.

  16. Circular Array Implementation Basic Idea: Allow the queue to wrap-around Implement with addition mod size: tail = (tail + 1) % queueSize; 4 4 J4 3 3 J3 J2 J1 2 2 N-2 J1 J2 N-2 J3 1 N-1 1 N-1 0 0

  17. Linked Queues • Problems with implementing queues on top of arrays • Sizing problems (bounds, clumsy resizing, …) • Non-circular Array – Data movement problem • Now that have the concepts of list nodes, can take advantage of to represent queues. • Need to determine appropriate way of: • Representing front and rear • Facilitating node addition and deletion at the ends.

  18. Front Rear Front Rear Rear HAT MAT CAT Linked Queues Add(Hat) Add(Mat) Add(Cat) Delete()

  19. Linked Queues Class QueueNode{ friend class Queue; public: QueueNode(int d, QueueNode * l); private: int data; QueueNode *link; };

  20. Linked Queues class Queue { public: Queue(); ~Queue(); void Add(const int); int* Delete(int&); bool isEmpty(); private: QueueNode* front; QueueNode* rear; void QueueEmpty(); }

  21. Front Rear Linked Queues Queue::Queue() { front = 0; rear = 0; } bool Queue::isEmpty() { return (front == 0); } 0 0

  22. Front Rear Rear HAT CAT Linked Queues void Queue::Add(const int y) { // Create a new node that contains data y // Has to go at end // Set current rear link to new node pointer // Set new rear pointer to new node pointer rear = rear->link = new QueueNode(y, 0); } MAT

  23. Front toDelete Front Rear HAT CAT Linked Queues int * Queue::Delete(int & retValue) { // handle empty case if (isEmpty()) { QueueEmpty(); return 0;} QueueNode* toDelete = front; retValue = toDelete.data; front = toDelete->link; delete toDelete; return &retValue; } returnValue HAT MAT

  24. Temp Temp Front Front Front Rear HAT CAT Queue Destructor Queue destructor needs to remove all nodes from head to tail. MAT if (front) { QueueNode* temp; while (front != rear) { temp = front; front = front -> link; delete temp; } delete front; front = rear = 0; } 0 0

  25. Front vs Delete • Implementation as written has to remove the item from the queue to read data value. • Some implementations provide two separate functions: • Front() which returns the data in the first element • Delete() which removes the first element from the queue, without returning a value.

  26. Queue Example: Radix Sort Also called bin sort: Repeatedly shuffle data into small bins Collect data from bins into new deck Repeat until sorted Appropriate method of shuffling and collecting? For integers, key is to shuffle data into bins on a per digit basis, starting with the rightmost (ones digit) Collect in order, from bin 0 to bin 9, and left to right within a bin

  27. Radix Sort: Ones Digit Data: 459 254 472 534 649 239 432 654 477 Bin 0 Bin 1 Bin 2 472 432 Bin 3 Bin 4 254 534 654 Bin 5 Bin 6 Bin 7 477 Bin 8 Bin 9 459 649 239 After Call: 472 432 254 534 654 477 459 649 239

  28. Radix Sort: Tens Digit Data: 472 432 254 534 654 477 459 649 239 Bin 0 Bin 1 Bin 2 Bin 3 432 534 239 Bin 4 649 Bin 5 254 654 459 Bin 6 Bin 7 472 477 Bin 8 Bin 9 After Call: 432 534 239 649 254 654 459 472 477

  29. Radix Sort: Hundreds Digit Data: 432 534 239 649 254 654 459 472 477 Bin 0 Bin 1 Bin 2 239 254 Bin 3 Bin 4 432 459 472 477 Bin 5 534 Bin 6 649 654 Bin 7 Bin 8 Bin 9 Final Sorted Data: 239 254 432 459 472 477 534 649 654

  30. Radix Sort Algorithm Begin with current digit as one’s digit While there is still a digit on which to classify { For each number in the master list, Add that number to the appropriate sublist keyed on the current digit For each sublist from 0 to 9 For each number in the sublist Remove the number from the sublist and append to a new master list Advance the current digit one place to the left. }

  31. Radix Sort and Queues What does radix sort have to do with queues? Each list (the master list (all items) and bins (per digit)) needs to be first in, first out ordered – perfect for a queue.

  32. A Quick Tangent • How fast have the sorts you’ve seen before worked? • Bubble, Insertion, Selection: O(n^2) • We will see sorts that are better, and in fact optimal for general sorting algorithms: • Merge/Quicksort: O(n log n) • How fast is radix sort?

  33. Analysis of Radix Sort • Let n be the number of items to sort • Outer loop control is on maximum length of input numbers in digits (Let this be d) • For every digit, • Assign each number to sort to a group (n operations) • Pull each number back into the master list (n operations) • Overall running time: 2 * n * d => O(n)

  34. Analysis of Radix Sort • O(n log n) is optimal for general sorting algorithms • Radix sort is O(n)? How does that work? • Radix sort is not a general sorting algorithm – It can’t sort arbitrary information – Rectangles objects, Automobiles objects, etc are no good. • Can sort items that can be broken into constituent pieces and whose pieces can be ordered • Integers (digits), Strings (characters)

More Related