COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Transform and Conquer Chapter 6. Transform and Conquer Solve problem by transforming into: a more convenient instance of the same problem (instance simplification)
Chapter 15 Heaps. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a heap abstract data structure Demonstrate.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Advanced Data Structures Chapter 16. Priority Queues Collection of elements each of which has a priority. Does not maintain a first-in, first-out discipline.
1 HeapSort CS 3358 Data Structures. 2 Heapsort: Basic Idea Problem: Arrange an array of items into sorted order. 1) Transform the array of items into.
1a) Create a max-heap by inserting the following integers into an initially empty heap (one by one): 6, 2, 4, 1, 8, 5, 3, 7, 9 We will refer to the resulting.
1 Heaps & Priority Queues (Walls & Mirrors - Remainder of Chapter 11)
© 2006 Pearson Addison-Wesley. All rights reserved12 B-1 Chapter 12 (continued) Tables and Priority Queues.
CMPT 225 Priority Queues and Heaps. Priority Queues Items in a priority queue have a priority The priority is usually numerical value Could be lowest.
TCSS 343, version 1.1 Algorithms, Design and Analysis Transform and Conquer Algorithms Presorting HeapSort.
Version TCSS 342, Winter 2006 Lecture Notes Priority Queues Heaps.
© 2006 Pearson Addison-Wesley. All rights reserved12-1 Chapter 12 Tables and Priority Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring.
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 TCSS 342, Winter 2005 Lecture Notes Priority Queues and Heaps Weiss Ch. 21, pp
© 2006 Pearson Addison-Wesley. All rights reserved12 A-1 Chapter 12 Heaps.
Chapter 12 B Priority Queues. © 2004 Pearson Addison-Wesley. All rights reserved 12 B-2 The ADT Priority Queue: A Variation of the ADT Table The ADT priority.
Fundamentals of Python: From First Programs Through Data Structures
Marc Smith and Jim Ten Eyck
CSE 373 Data Structures and Algorithms Lecture 13: Priority Queues (Heaps)
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2010 transform & conquer  transform-and-conquer approach  balanced search trees o AVL, 2-3 trees,
CSC 172 DATA STRUCTURES. Priority Queues Model Set with priorities associatedwith elements Priorities are comparable by a < operator Operations Insert.
Heapsort Based off slides by: David Matuszek
1 Hash Tables  a hash table is an array of size Tsize  has index positions 0.. Tsize-1  two types of hash tables  open hash table  array element type.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
data ordered along paths from root to leaf
Chapter 11 Heap. Overview ● The heap is a special type of binary tree. ● It may be used either as a priority queue or as a tool for sorting.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
CSE 250 September 29 – October 3, A NNOUNCEMENTS Homework 4 due 10/5 Project 1 posted for 10/6 Exam 2 10/8 No classes meet 10/9 Project 1 due 10/26.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
1 Joe Meehean.  We wanted a data structure that gave us... the smallest item then the next smallest then the next and so on…  This ADT is called a priority.
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Fall 2015CS202 - Fundamental Structures of Computer Science II1 Heaps Appropriate for problems that must manage data by value. Some important operations.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
CHAPTER 5 PRIORITY QUEUES (HEAPS) §1 ADT Model Objects: A finite ordered list with zero or more elements. Operations:  PriorityQueue Initialize( int.
Data Structure II So Pak Yeung Outline Review  Array  Sorted Array  Linked List Binary Search Tree Heap Hash Table.
Week 13 - Friday.  What did we talk about last time?  Sorting  Insertion sort  Merge sort  Started quicksort.
Lecture 15 Jianjun Hu Department of Computer Science and Engineering University of South Carolina CSCE350 Algorithms and Data Structure.
Heaps & Priority Queues
Tree Data Structures. Heaps for searching Search in a heap? Search in a heap? Would have to look at root Would have to look at root If search item smaller.
Chapter 13 Priority Queues. 2 Priority queue A stack is first in, last out A queue is first in, first out A priority queue is least-in-first-out The “smallest”
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables I.
Sorting Dr. Yingwu Zhu. Heaps A heap is a binary tree with properties: 1. It is complete Each level of tree completely filled Except possibly bottom level.
HEAPS. Review: what are the requirements of the abstract data type: priority queue? Quick removal of item with highest priority (highest or lowest key.
Internal and External Sorting External Searching
Heaps A heap is a binary tree that satisfies the following properties: Structure property: It is a complete binary tree Heap-order property: Each node.
CS 367 Introduction to Data Structures Lecture 8.
CSI 312 Dr. Yousef Qawqzeh Heaps and Priority Queue.
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
2 Binary Heaps What if we’re mostly concerned with finding the most relevant data?  A binary heap is a binary tree (2 or fewer subtrees for each node)
Course: Programming II - Abstract Data Types HeapsSlide Number 1 The ADT Heap So far we have seen the following sorting types : 1) Linked List sort by.
Spring 2016CS202 - Fundamental Structures of Computer Science II1 Tables Appropriate for problems that must manage data by value. Some important operations.
Tables and Priority Queues
Tables and Priority Queues
CS202 - Fundamental Structures of Computer Science II
CS202 - Fundamental Structures of Computer Science II
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
CS Data Structures Chapter 17 Heaps Mehmet H Gunes
Ch. 12 Tables and Priority Queues
Tables and Priority Queues
Sorting Dr. Yingwu Zhu.
Chapter 12 Heap ADT © 2011 Pearson Addison-Wesley. All rights reserved.
Heaps and priority queues
Tables and Priority Queues
EE 312 Software Design and Implementation I
Presentation transcript:

COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III

2 Topics Priority Queues Heaps Heap Sort

3 ADT Priority Queue Appropriate for data that don't need to be searched by search key Example: Emergency Room in a hospital Patients are treated in the order of their arrival Some priority would be assigned for some patients The next available doctor should treat the patient with the highest priority A priority value is added to the record representing the items and is assigned to indicate the task's priority for completion Larger priority values indicate highest priority

4 ADT Priority Queue

5 Possible Implementations Array-Based Items are maintained in ascending sorted order of priority value Item with highest priority value is at the end of the array pqDelete returns the item in Items [Size - 1] pqInsert uses binary search to find the correct position, then shift array elements to make room to the new item

6 ADT Priority Queue Possible Implementations Array-Based Items are maintained in ascending sorted order of priority value Item with highest priority value is at the end of the array pqDelete returns the item in Items [Size - 1] pqInsert uses binary search to find the correct position, then shift array elements to make room to the new item (O(?))

7 ADT Priority Queue Possible Implementations Reference-Based??

8 ADT Priority Queue Possible Implementations Reference-Based Items are maintained in descending order of priority values The highest priority value is at the beginning of the linked list pqDelete returns the item in PQ_Head, then changes PQ_Head to “point” to the next item (O(?)) pqInsert must traverse the list to find the correct position, then insert the element by “pointer” manipulation (O(?))

9 ADT Priority Queue Possible Implementations BST ???

10 ADT Priority Queue Possible Implementations BST pqInsert is the same as TableInsert (O(?)) pqDelete is easier because the highest priority value is always in the rightmost node of the tree (O(?))

11 ADT Priority Queue Conclusion A BST is good for both tables & priority queues If the table application primarily involves retrievals & traversals, the balance of the tree isn't affected Because priority queues involve mostly insertions & deletions, which can affect the shape of the tree, a balanced variation of the tree will be needed If you know the maximum size of the priority queue, an array-based implementation is better

12 Review A priority queue orders its items by their ______. position value priority value size

13 Review The first item to be removed from a priority queue is the item ______. in the front of the priority queue in the end the priority queue with the highest value with the highest priority value

14 Review In an array-based implementation of the priority queue, the pqDelete operation returns the item in ______. items[size] items[0] items[size-1] items[size+1]

15 Review In a linear implementation of the priority queue based on a linked list, the item with the highest priority value is located ______. at the beginning of the linked list at the end of the linked list in the middle of the linked list at a random location in the linked list

16 Review In a binary search tree implementation of the ADT table, the item with the highest priority value is always in the ______. root of the tree leftmost node of the tree rightmost node of the tree leftmost node at level 1 of the tree

17 Heaps Heap: A complete binary tree with the following characteristics: The tree is Empty binary tree, or Its Root contains a search key >= (for a Maxheap) or <= (for Minheap) Search key of its children, and The subtrees are also Heaps The search keys of the children have no relationship; you don't know which child has the larger (smaller) search key The heap is always complete and balanced

18 Heaps Special Heaps: Max-Heap: The heap with the largest item's search key in its root Min-Heap: The heap with the smallest item's search key in its root Semi-Heap: When the root isn't the largest, but both subtrees are heaps

19 Heaps max heap min heap min heap

20 ADT Heap Operations

21 ADT Heap's Array-Based Implementation An array and an integer counter are needed Array of heap items Size: number of items in the heap If the root is deleted, a semi-heap might result. In such case the heap has to be rebuilt to preserve the heap property

22 ADT Heap's Array-Based Implementation Example: Deletion Delete 10 IndexContents

23 ADT Heap's Array-Based Implementation Example: Deletion Delete 10 we get 2 disjoint heaps IndexContents st Heap2 nd Heap

24 ADT Heap's Array-Based Implementation Example : Deletion Put 5 instead of 10 We get a semi-heap IndexContents

25 ADT Heap's Array-Based Implementation Example: Deletion Trickle down We get a heap back IndexContents

26 ADT Heap's Array-Based Implementation Example: Deletion heapRebuild (items, root, size) //convert a semiheap into a heap

27 ADT Heap's Array-Based Implementation Example: Insertion Insert

28 ADT Heap's Array-Based Implementation Example: Insertion Tickle-up

29 ADT Heap's Array-Based Implementation Example: Insertion Tickle-up

30 ADT Heap's Array-Based Implementation public class Heap { private int MAX_HEAP =100; private KeyedItem [] items; // array of heap items private int size; // number of heap items public Heap () { items = new KeyedItem [MAX_HEAP]; size =0; } public bool heapIsEmpty() { return size == 0; } // end heapIsEmpty

31 ADT Heap's Array-Based Implementation public class Heap { private int MAX_HEAP =100; private KeyedItem [] items; // array of heap items private int size; // number of heap items public Heap () { items = new KeyedItem [MAX_HEAP]; size =0; } public bool heapIsEmpty() { return size == 0; } // end heapIsEmpty

32 ADT Heap's Array-Based Implementation public void heapInsert(KeyItem newItem) throw HeapException // Method: Inserts the new item after the last item in the heap and trickles it up to // its proper position. The heap is full when it contains MAX_HEAP items. { if (size >= MAX_HEAP) throw HeapException("HeapException: Heap full"); // place the new item at the end of the heap items[size] = newItem; // trickle new item up to its proper position int place = size; int parent = (place - 1)/2; while ( (parent >= 0) && (items[place].getKey().compareTo( items[parent].getKey()) )>0) { // swap items[place] and items[parent] KeyedItem temp = items[parent]; items[parent] = items[place]; items[place] = temp; place = parent; parent = (place - 1)/2; } // end while ++size; } // end heapInsert

33 ADT Heap's Array-Based Implementation public KeyedItem heapDelete() // delete the item in the root of a heap { KeyedItem rootItem=null; if (!heapIsEmpty()) { rootItem = items[0]; items[0] = items[--size]; heapRebuild(0); } // end if return rootItem; } // end heapDelete

34 ADT Heap's Array-Based Implementation protected void heapRebuild(int root) { // if the root is not a leaf and the root's search key is less than the larger // of the search keys in the root's children int child = 2 * root + 1; // index of root's left child, if any if ( child < size ) { // root is not a leaf, so it has a left child at child int rightChild = child + 1; // index of right child, if any // if root has a right child, find larger child if ( (rightChild 0) child = rightChild; // index of larger child // if the root's value is smaller than the value in the larger child, swap values if ( items[root].getKey().compareTo( items[child].getKey())<0 ) { KeyedItem temp = items[root]; items[root] = items[child]; items[child] = temp; // transform the new subtree into a heap heapRebuild(child); } // end if // if root is a leaf, do nothing } // end heapRebuild // End of implementation file.

35 ADT Priority Queue's Heap Implementation Priority queue operations are analog to heap operations (how?) Priority value in a priority queue corresponds to heap item's search key Priority queue implementation can reuse the heap class If you know the maximum number of items in the priority queue, the heap is a better implementation Heap is always balanced

36 ADT Priority Queue's Heap Implementation class PriorityQueue { private Heap h; public PriorityQueue () { h= new Heap (); } public boolean pqIsEmpty() { return h.heapIsEmpty(); } // end pqIsEmpty

37 ADT Priority Queue's Heap Implementation class PriorityQueue { private Heap h; public PriorityQueue () { h= new Heap (); } public boolean pqIsEmpty() { return h.heapIsEmpty(); } // end pqIsEmpty

38 ADT Priority Queue's Heap Implementation public void pqInsert(KeyedItem newItem) throws PQueueException { try { h.heapInsert(newItem); } catch (HeapException e) { throw new PQueueException( "PQueueException: Priority queue full"); } // end catch } // end pqInsert void KeyedItem pqDelete() { return h.heapDelete(priorityItem); } // end pqDelete }// End of implementation file.

39 ADT Priority Queue's Heap Implementation public void pqInsert(KeyedItem newItem) throws PQueueException { try { h.heapInsert(newItem); } catch (HeapException e) { throw new PQueueException( "PQueueException: Priority queue full"); } // end catch } // end pqInsert void KeyedItem pqDelete() { return h.heapDelete(priorityItem); } // end pqDelete }// End of implementation file.

40 Heap-Sort A heap is used to sort an array of items Idea: 1. First transform the array into a heap 2. The array is partitioned into two regions - the Heap region and the Sorted region 3. Delete the root from the heap 4. Move the root from the heap region to the sorted region 5. Rebuild the heap 6. Repeat From step 3

41 Heap-Sort Original array: 1. Transform array into a heap: Store into a balance BT Call heapRebuild on the leaves from right to left

42 Heap-Sort 2. Partition array into two regions Heap region and sorted region

43 Heap-Sort 3. Delete root from heap

44 Heap-Sort 4. Move root from heap to sorted region Heap regionSorted region

45 Heap-Sort 5. Rebuild the heap

46 Heap-Sort 6. Repeat From step 3, Heap region Sorted region

47 Review A heap in which the root contains the item with the largest search key is called a ______. minheap maxheap complete heap binary heap

48 Review A heap in which the root contains the item with the smallest search key is called a ______. minheap maxheap complete heap binary heap

49 Review A heap is a ______. general tree table full binary tree complete binary tree

50 Review A semiheap is a ______. table complete binary tree general tree full binary tree

51 Review In an array-based implementation of a heap, the number of array items that must be swapped to transform a semiheap of n nodes into a heap is ______. n n + 1 log 2 n log 2 (n + 1)

52 Review In an array-based implementation of a heap, the heapDelete operation is ______. O(1) O(n) O(n 2 ) O(log n)

53 Review In an array-based implementation of a heap, the parent of the node in items[i] is always stored in ______. items[i/2] items[(i-1)/2] items[i-2] items[(i-2)/2]

54 Review In an array-based implementation of a heap, the heapInsert operation is ______. O(1) O(n) O(n 2 ) O(log n)

55 Review The heapsort is ______ in the worst case. O(n) O(log n) O(n * log n) O(n 2 )

56 Review The heapsort is ______ in the average case. O(1) O(n) O(log n) O(n * log n)

57 Review Which of the following is true about the heapsort? the heapsort does not require a second array the heapsort is more efficient than the mergesort in the worst case the heapsort is more efficient than the mergesort in the average case the heapsort is better than the quicksort in the average case