INF2220: algorithms and data structures Series 4

Similar documents
INF2220: algorithms and data structures Series 1

Chapter 6 Heaps. Introduction. Heap Model. Heap Implementation

Heap Model. specialized queue required heap (priority queue) provides at least

CSCI-1200 Data Structures Fall 2018 Lecture 23 Priority Queues II

Data Structures and Algorithms

Binary heaps (chapters ) Leftist heaps

CMSC 341 Leftist Heaps

CMSC 341 Lecture 15 Leftist Heaps

CMSC 341 Lecture 15 Leftist Heaps

Thus, it is reasonable to compare binary search trees and binary heaps as is shown in Table 1.

INF2220: algorithms and data structures Series 3

COMP : Trees. COMP20012 Trees 219

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

CSCI-1200 Data Structures Spring 2016 Lecture 22 Priority Queues, part II (& Functors)

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

CMSC 341. Binary Heaps. Priority Queues

CSE373 Fall 2013, Midterm Examination October 18, 2013

Sorting and Searching

INF2220: algorithms and data structures Series 1

Priority Queues Heaps Heapsort

CMSC 341 Lecture 14: Priority Queues, Heaps

Priority Queues (Heaps)

Recall: Properties of B-Trees

CE 221 Data Structures and Algorithms

Week 10. Sorting. 1 Binary heaps. 2 Heapification. 3 Building a heap 4 HEAP-SORT. 5 Priority queues 6 QUICK-SORT. 7 Analysing QUICK-SORT.

Sorting and Searching

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

l So unlike the search trees, there are neither arbitrary find operations nor arbitrary delete operations possible.

9. Heap : Priority Queue

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

Priority Queues (Heaps)

Maintain binary search tree property nodes to the left are less than the current node, nodes to the right are greater

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

Heap sort. Carlos Moreno uwaterloo.ca EIT

CS350: Data Structures Heaps and Priority Queues

Trees. A tree is a directed graph with the property

l Heaps very popular abstract data structure, where each object has a key value (the priority), and the operations are:

CSCI 136 Data Structures & Advanced Programming. Lecture 22 Fall 2018 Instructor: Bills

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

CS 234. Module 8. November 15, CS 234 Module 8 ADT Priority Queue 1 / 22

Computer Science 210 Data Structures Siena College Fall Topic Notes: Binary Search Trees

Heap sort. Carlos Moreno uwaterloo.ca EIT

Binary Heaps. CSE 373 Data Structures Lecture 11

Data Structures Week #8. Heaps (Priority Queues)

INF2220: algorithms and data structures Series 5

The priority is indicated by a number, the lower the number - the higher the priority.

Priority Queues. Lecture15: Heaps. Priority Queue ADT. Sequence based Priority Queue

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

Test #2. Login: 2 PROBLEM 1 : (Balance (6points)) Insert the following elements into an AVL tree. Make sure you show the tree before and after each ro

CSE 332: Data Structures & Parallelism Lecture 3: Priority Queues. Ruth Anderson Winter 2019

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

Algorithms and Data Structures

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

Binary Trees. Directed, Rooted Tree. Terminology. Trees. Binary Trees. Possible Implementation 4/18/2013

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

Hash Tables. CS 311 Data Structures and Algorithms Lecture Slides. Wednesday, April 22, Glenn G. Chappell

Today s Outline. The One Page Cheat Sheet. Simplifying Recurrences. Set Notation. Set Notation. Priority Queues. O( 2 n ) O( n 3 )

CS 315 April 1. Goals: Heap (Chapter 6) continued review of Algorithms for Insert DeleteMin. algoritms for decrasekey increasekey Build-heap

CSE 373 Autumn 2010: Midterm #2 (closed book, closed notes, NO calculators allowed)

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

Binary Search Trees Treesort

Tables, Priority Queues, Heaps

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

Section 4 SOLUTION: AVL Trees & B-Trees

Second Examination Solution

Advanced Algorithms. Class Notes for Thursday, September 18, 2014 Bernard Moret

examines every node of a list until a matching node is found, or until all nodes have been examined and no match is found.

Priority Queues and Heaps. Heaps of fun, for everyone!

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

Figure 1: A complete binary tree.

CSE 5311 Notes 4a: Priority Queues

CSCI2100B Data Structures Heaps

Solved by: Syed Zain Ali Bukhari (BSCS)

Algorithms. Deleting from Red-Black Trees B-Trees

Chapter 6 Heapsort 1

I2206 Data Structures TS 6: Binary Trees - Binary Search Trees

CSE 373 Sample Midterm #2 (closed book, closed notes, calculators o.k.)

Programming II (CS300)

Dictionaries. Priority Queues

Section 1: True / False (1 point each, 15 pts total)

Arrays aren t going to work. What can we do? Use pointers Copy a large section of a heap, with a single pointer assignment

ITI Introduction to Computing II

Readings. Priority Queue ADT. FindMin Problem. Priority Queues & Binary Heaps. List implementation of a Priority Queue

PRIORITY QUEUES AND HEAPS

UNIT III BALANCED SEARCH TREES AND INDEXING

CSE 214 Computer Science II Heaps and Priority Queues

Algorithms. AVL Tree

CSE 241 Class 17. Jeremy Buhler. October 28, Ordered collections supported both, plus total ordering operations (pred and succ)

Data Structures Lesson 9

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

Computer Science 302 Spring 2007 Practice Final Examination: Part I

Priority Queues Heaps Heapsort

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

CSE373: Data Structures & Algorithms Lecture 9: Priority Queues and Binary Heaps. Linda Shapiro Spring 2016

Heaps, Heap Sort, and Priority Queues.

Transcription:

Universitetet i Oslo Institutt for Informatikk A. Maus, R.K. Runde, I. Yu INF2220: algorithms and data structures Series 4 Topic Priority Queues and Heaps (Exercises with hints for solution) Issued: 4. 09. 20 Classroom Exercise Draw the structure of a binary heap. after these priorities have been inserted: 9, 34, 23, 6, 4, 89, 24, 29,, 6, 2. 2. after two deletemin operations. Solution: One may say: the structure conditions ( complete binary tree) makes the procedure necessarily deterministic (if the order of insertions (and deletions) is given (and all priorities are different)). So there can be only one correct solution. For analogous exercises for BSTs, there are logically two different implementations for deletion, which give sligtly different outcomes. A practical consequece: when doing such an exercise, there is no obvious shortcut, i.e. a way to fill in the numbers into the tree without doing it step by step. 9 6 23 2 23 9 2 89 24 29 6 89 24 34 29 6 4 34 4 Figure : Solution Exercise. Figure 2: Solution Exercise.2 Exercise 2 (Binary heap) Draw the structure of a binary heap. after these priorities have been inserted: 0, 2,, 4, 6,, 8,, 3, 9,, 4,, 3, 2.

Series 4 (+ Hints for solutions) 4. 09. 20 2. after three deletemin operations. Solution: [of Exercise 2] There s nothing new in this exercise, it s the same as the previous one. 3 6 4 4 2 9 0 3 8 Figure 3: Solution Exercise 2. 4 6 3 0 8 4 2 9 Figure 4: Solution Exercise 2.2 Exercise 3 (Leftist Heap I) Is the tree a leftist heap? Explain your answer. 0 2 20 2 0 99 Figure : Exercise 3 Exercise 4 (Leftist Heap II). Merge the two leftist heaps. Remember to maintain the structure of a leftist heap. 2. Perform a deletemin operation on the resulting leftist heap from Exercise 4. 2

Series 4 (+ Hints for solutions) 4. 09. 20 22 0 2 2 20 0 99 Figure 6: Exercise 4. Solution: Solution for Exercise 3 and 4. For the first tree: it looks already suspicious, but of course that s not an answer. There are two conditions on such trees. One is the condition in the numbers (the priorities ). This one is alright. As for the structural condition. We need to check the official definition, i.e., the condition on npl s for all nodes. One point where the condition is violated is node and it s children: the null pointer lenght of s subtree is smaller than that of the right one, that is, npl(20) = 0 < = npl(2). Note in particular, that locally at the root node, the structural condition for leftist heaps is ok! Both direct children have a nlp of! A correct answer in an exam would require that one points to (at least) one node where where the condition is concretely broken. Of course, also node is not a leftist-heap since it s right-subtree is not, but the full explanation must locate the point where it directly breaks. The fact that node is the only place where the ordering requirement is broken means: one can repair it (in constant time) by simply swapping the two subtrees (even if after the swapping, the right-hand subtree still looks larger, now it s ok). That s the tree which is used in the second part of the exercise to do a merge. merge (, 2 2 ) => merge (, 2 2 ) => merge ( 2, 2 2 ) => merge ( 2, ) // the r i g h t had o f 22 = 2 2 [, 2 ] <= [ 2 0 [ 0, 9 9 ], 2 2 [, 2 ] ] <= [ [ 2 0 [ 0, 9 9 ], 2 2 [, 2 ] ], [ 0, ] ] <= // that s not l e f t i s t = swap [ 2 2 [, 2 ] ], [ 0, ], [ 2 0 [ 0, 9 9 ] ] 0 2 2 20 0 99 22 Figure : Result of the merge (Ex. 4.) 3

Series 4 (+ Hints for solutions) 4. 09. 20 For the third exercise: Here s one easy way (which is also the one from the book). Now that we have merging, deleting a node splits the heap into two. Since the recursive definition of leftists heaps (all decent tree definitions are recursive), the two sub-trees are again leftist heaps, so we can merge them with the procedure we have learnt. The result is given 0 2 20 0 99 22 2 Figure 8: Result of the merge (Ex. 4.2) Another idea is; to use the delete minimum as is done for the perfectly balanced tree. That s also possible, actually, in a way that is simpler, because the requirements (the balance condition) is not as strict. The way that deletion for the min-heaps is done: the perfect balance must not be destroyed. That s done by replacing the root by the last leaf on the bottom (from left to right). Since the tree is stored in an array, and since we need to remember which is the last leaf we have direct access to that and can immediately copy that to the root and then percolate it down. Note that percolating down there does not change the structure. We can achieve something like that also here, except that it s not so easy to find a leaf, we can of course search for it. The main question is: which leaf should we take. Exercise Show that the element with the lowest priority (highest number). can be found in one of the leaf-nodes 2. that it can be found in an arbitrary leaf-node (it s sufficient to show that the requirements of a binary heap holds with different arrangements) 3. show that a binary heap with an even number of elements (N) will have exactly N/2 leaf-nodes. This assignment is perhaps a bit difficult, try to think about the data-structure we used to represent a binary heap Exercise 6 A file contains only spaces and digits in the following frequency: space (9), a (), b (), d (3), e (), f (3), h (), i (), k (), n (4), o (), r (), s (), t (2), u (), v (). Construct the Huffman code. Solution: 4

Series 4 (+ Hints for solutions) 4. 09. 20 sp a r e d f n b h t i k o s u v One possible tree: Exercise (Huffman) A file contains only colons, spaces, newlines, commas, and digits in the following frequency: colon (00), space (60), newline (00), comma (0), 0 (43), (242), 2 (6), 3 (9), 4 (8), (20), 6 (4), (99), 8 (20), 9 (2). Construct the Huffman code. Solution: One possible tree: Lab Exercise 8 Implement the interface below with a BinaryHeap. interface HeapInterface<T>{ } public void insert(int pri, T o); public T deletemin(); Exercise 9 Make a program which sorts a sequence of numbers using a heap. The alternative to store a special priority value like or null or similar to indicate that the node is not there is not too smart, even if that would work.

Series 4 (+ Hints for solutions) 4. 09. 20 Exercise 0 A binary heap is a special case of a DHeap, where the heap is allowed to have D children. i.e., a binary heap is a DHeap with D == 2. Implement a TernaryHeap (DHeap with D == 3) HINT: now we get three children to examine to find out whether or not they have a higher priority then ourselves, functions to calculate where the elements can be found in the array is given below. private int dad(int pos){ return (int) Math.ceil( ((double) pos -.0) / 3.0); } private int first(int pos){ return (3 * (pos - )) + 2; } private int second(int pos){ return (3 * (pos - )) + 3; } private int third(int pos){ return (3 * (pos - )) + 4; } Exercise What is the maximum height of a TernaryHeap with N elements? 6