תרגול 9 Heaps Lempel-Ziv. Heaps Heap A binary heap can be considered as a complete binary tree, (the last level is full from the left to a certain point).

Slides:



Advertisements
Similar presentations
CS16: Introduction to Data Structures & Algorithms
Advertisements

Chapter 23 Minimum Spanning Tree
© 2004 Goodrich, Tamassia Heaps © 2004 Goodrich, Tamassia Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of.
1 Designing Hash Tables Sections 5.3, 5.4, Designing a hash table 1.Hash function: establishing a key with an indexed location in a hash table.
Hash Tables.
Priority Queues Two kinds of priority queues: Min priority queue. Max priority queue.
Chapter 12 Binary Search Trees
Foundations of Data Structures Practical Session #7 AVL Trees 2.
COL 106 Shweta Agrawal and Amit Kumar
Heaps1 Part-D2 Heaps Heaps2 Recall Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is a pair (key, value)
CS Section 600 CS Section 002 Dr. Angela Guercio Spring 2010.
Priority Queue and Heap 1. 2 Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu.
Binary Heaps CSE 373 Data Structures Lecture 11. 2/5/03Binary Heaps - Lecture 112 Readings Reading ›Sections
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
Heaps & Priority Queues Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Priority Queues. Container of elements where each element has an associated key A key is an attribute that can identify rank or weight of an element Examples.
3-Sorting-Intro-Heapsort1 Sorting Dan Barrish-Flood.
Tirgul 7 Heaps & Priority Queues Reminder Examples Hash Tables Reminder Examples.
Chapter 10 Search Structures Instructors: C. Y. Tang and J. S. Roger Jang All the material are integrated from the textbook "Fundamentals of Data Structures.
Priority Queues1 Part-D1 Priority Queues. Priority Queues2 Priority Queue ADT (§ 7.1.3) A priority queue stores a collection of entries Each entry is.
Heapsort CIS 606 Spring Overview Heapsort – O(n lg n) worst case—like merge sort. – Sorts in place—like insertion sort. – Combines the best of both.
1 Chapter 8 Priority Queues. 2 Implementations Heaps Priority queues and heaps Vector based implementation of heaps Skew heaps Outline.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Heapsort Based off slides by: David Matuszek
Compiled by: Dr. Mohammad Alhawarat BST, Priority Queue, Heaps - Heapsort CHAPTER 07.
ADT Table and Heap Ellen Walker CPSC 201 Data Structures Hiram College.
Binary Heap.
The Binary Heap. Binary Heap Looks similar to a binary search tree BUT all the values stored in the subtree rooted at a node are greater than or equal.
Chapter 21 Binary Heap.
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.
Data Structures Week 8 Further Data Structures The story so far  Saw some fundamental operations as well as advanced operations on arrays, stacks, and.
Chapter 21 Priority Queue: Binary Heap Saurav Karmakar.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
CSC 213 – Large Scale Programming Lecture 15: Heap-based Priority Queue.
Priority Queue. Priority Queues Queue (FIFO). Priority queue. Deletion from a priority queue is determined by the element priority. Two kinds of priority.
PRIORITY QUEUES AND HEAPS CS16: Introduction to Data Structures & Algorithms Tuesday, February 24,
Algorithms and data structures Protected by
Priority Queues and Heaps. October 2004John Edgar2  A queue should implement at least the first two of these operations:  insert – insert item at the.
Foundations of Data Structures Practical Session #8 Heaps.
Data Structure II So Pak Yeung Outline Review  Array  Sorted Array  Linked List Binary Search Tree Heap Hash Table.
CPSC 252 Binary Heaps Page 1 Binary Heaps A complete binary tree is a binary tree that satisfies the following properties: - every level, except possibly.
David Luebke 1 12/23/2015 Heaps & Priority Queues.
S. Raskhodnikova and A. Smith. Based on slides by C. Leiserson and E. Demaine. 1 Adam Smith L ECTURES Priority Queues and Binary Heaps Algorithms.
Heapsort. What is a “heap”? Definitions of heap: 1.A large area of memory from which the programmer can allocate blocks as needed, and deallocate them.
8 January Heap Sort CSE 2011 Winter Heap Sort Consider a priority queue with n items implemented by means of a heap  the space used is.
Heaps & Priority Queues
CSC 413/513: Intro to Algorithms Solving Recurrences Continued The Master Theorem Introduction to heapsort.
Internal and External Sorting External Searching
Priority Queues and Heaps Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University.
Priority Queues CS 110: Data Structures and Algorithms First Semester,
Heaps © 2010 Goodrich, Tamassia. Heaps2 Priority Queue ADT  A priority queue (PQ) stores a collection of entries  Typically, an entry is a.
1 Chapter 6 Heapsort. 2 About this lecture Introduce Heap – Shape Property and Heap Property – Heap Operations Heapsort: Use Heap to Sort Fixing heap.
Week 13 - Wednesday.  What did we talk about last time?  NP-completeness.
"Teachers open the door, but you must enter by yourself. "
Recitation 3 (Heap Sort and Binary Search Tree)
Heaps, Heap Sort and Priority Queues
Priority Queues Chuan-Ming Liu
Heaps © 2010 Goodrich, Tamassia Heaps Heaps
Heap Sort Example Qamar Abbas.
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
original list {67, 33,49, 21, 25, 94} pass { } {67 94}
Part-D1 Priority Queues
תרגול 9 Heaps Lempel-Ziv.
Draw pictures to indicate the subproblems middleMax solves at each level and the resulting maxPtr and PrevPtr for each on this linked list:
Heaps © 2014 Goodrich, Tamassia, Goldwasser Heaps Heaps
HEAPS.
Algorithms: Design and Analysis
Heaps By JJ Shepherd.
Presentation transcript:

תרגול 9 Heaps Lempel-Ziv

Heaps Heap A binary heap can be considered as a complete binary tree, (the last level is full from the left to a certain point). Maximum- Heap For each node x, x ≥ left(x) and x ≥ right(x) The root in a Maximum-Heap is the maximal element in the heap Minimum- Heap For each node x, x ≤ left(x) and x ≤ right(x) The root in a Minimum-Heap is the minimal element in the heap Heap-Array

Heaps Actions on Heaps  Insert ~ O(log(n))  Max ~ O(1)  Extract-Max ~ O(log(n))  Build-Heap ~ O(n)  Down-Heapify(H, i) – same as MaxHeapify seen in class but starting in the node in index i ~ O(log(n))  Up-Heapify(H, i) – Fixing the heap going from node in index i to the root as in Insert() ~ O(log(n))

Heaps דוגמה : הוסיפו את 9 1. מוסיפים את הערך 9 כעלה 2. מבצעים Up-Heapify לתיקון הערימה Heap_size קטן מאביו – מבצעים החלפה

Heaps דוגמה : הוסיפו את 9 1. מוסיפים את הערך 9 כעלה 2. מבצעים Up-Heapify לתיקון הערימה Heap_size קטן מאביו – מבצעים החלפה גדול מאביו – מסיימים

Heaps דוגמה : כעת בצעו Extract-min 1. מוציאים את השורש ( ושומרים את ערכו ) 2. מעבירים לשורש את העלה האחרון 3. מבצעים Down-Heapify מהשורש לתיקון הערימה Heap_size Key = 7 17

דוגמה : כעת בצעו Extract-min 1. מוציאים את השורש ( ושומרים את ערכו ) 2. מעבירים לשורש את העלה האחרון 3. מבצעים Down-Heapify מהשורש לתיקון הערימה Heaps Heap_size Key = 7 גדול מבנו הקטן – מבצעים החלפה

דוגמה : כעת בצעו Extract-min 1. מוציאים את השורש ( ושומרים את ערכו ) 2. מעבירים לשורש את העלה האחרון 3. מבצעים Down-Heapify מהשורש לתיקון הערימה 4. מחזירים את הערך שנשמר Heaps Heap_size Key = 7 גדול מבנו הקטן – מבצעים החלפה קטן מבנו הקטן – מסיימים

Question 3 בערימה H שמיוצגת בעזרת מערך, הציעו אלגוריתם להוצאת הערך במיקום ה -i ( הניחו כי i קטן מגודל הערימה ). מה זמן הריצה של האלגוריתם ?

14 Question 3 הדגמה : בצעו Extract(H,2)

Question 3 בערימה H שמיוצגת בעזרת מערך, הציעו אלגוריתם להוצאת הערך במיקום ה -i ( הניחו כי i קטן מגודל הערימה ). מה זמן הריצה של האלגוריתם ? Solution: Extract(H, i) key  H[i] H[i]  H[heap_size] /*Deleting the i'th element and replacing it with the last element*/ heap_size  heap_size − 1 /*Effectively shrinking the heap*/ Down-Heapify(H, i)/*Subtree rooted in H[i] is legal heap*/ Up-Heapify(H, i)/*Area above H[i] is legal heap*/ return key H[heap_size] בעומק גדול יותר מ H[i] ( או לפחות באותו עומק ). אם כך, מדוע ייתכן שנצטרך לבצע up-heapify?

14 Question 3 הדגמה : בצעו Extract(H,2) key  H[i] H[i]  H[heap_size] heap_size -- Down-Heapify(H, i) Up-Heapify(H, i) return key Heap_size 14 Key = 11 i גדול מבנו הקטן – מבצעים החלפה קטן מבנו הקטן – מסיימים גדול מאביו – מסיימים

Question 1 Given a maximum heap H, What is the time complexity of finding the 3 largest keys in H ? What is the time complexity of finding the C largest keys in H ? (C is a constant)

Question 1 Solution: It takes O(1) to find the 3 maximal keys in H. The 3 maximal keys in H are: – The root – The root's maximal son y – The largest among y's maximal son and y's sibling Finding the C largest keys in H can be done in a similar way: – The i th largest key is one of at most i keys, the sons of the i-1 largest key that have not been taken yet, thus can be found in O(i) time. – Finding the C largest keys takes O(C 2 ) = O(1) – (Another solution would be ordering all the keys in the first C levels of the heap)

Question 1 Given a maximum heap H, What is the time complexity of finding the 3 largest keys in H ? What is the time complexity of finding the C largest keys in H ? (C is a constant) What if C is not constant?

Question 1 Solution: If C is not constant we have to be more efficient. We will use a new heap, where we will store nodes of the original heap so that for each node entered we will have it sons as put in this new heap but we also preserve access to its sons as in the original heap. We first enter the root to the new heap. Then C times we do Extract-Max() on the new heap while at each time we Insert the original sons (the sons as in the original heap) to the new heap. The logic is as before only this time since the new heap has at most C elements we get O(C*log(C)). Note that we do not change the original heap at any point.

Question 1 הדגמה : מצאו את 5 המפתחות הקטנים ביותר בערימה בעזרת האלגוריתם נכנס לערימה החדשה 2.7 יוצא, 11 ו 13 נכנסים 3.11 יוצא, 12 ו 21 נכנסים 4.12 יוצא, 14 ו 51 נכנסים 5.13 יוצא, 17 ו 20 נכנסים 6.14 יוצא

Question 2 Analyze the complexity of finding the i smallest elements in a set of size n using each of the following: – Sorting – Priority Queue Sorting Solution: – Sort the numbers using algorithm that takes O(nlogn) – Find the i smallest elements in O(i) – Total = O(i+nlogn)=O(nlogn) Priority Queue Solution: – Build a minimum heap in O(n) – Execute Extract-Min i times in O(ilogn) – Total = O(n+ilogn). (if we use Q1: O(n+ilogi) ) Note: n+ilogn = Θ(max(n,ilogn)) and clearly n+ilogn = O(nlogn) (and faster if i ≠ Θ(n))

Question 4 You are given two min-heaps H 1 and H 2 with n 1 and n 2 keys respectively. Each element of H 1 is smaller than each element of H 2. How can you merge H 1 and H 2 into one heap H (with n 1 +n 2 keys) using only O(n 2 ) time? (Assume both heaps are represented in arrays of size > n 1 +n 2 )

Question 4

Question 6 Suppose that you had to implement a priority queue that only needed to store items whose priorities were integer values between 0 and k. Describe how a priority queue could be implemented so that insert() has complexity O(1) and RemoveMin() has complexity O(k). (Hint: This is very similar to a hash table.)

Question 6 Solution: Use an array A of size k+1 of linked lists. The linked list in the i th slot stores entries with priority i. To insert an item into the priority queue with priority i, append it to the linked list in the i th slot. E.g., insert(v) – A[v.priority].add-to-tail(v)

Question 6 Solution: To remove an item from the queue, scan the array of lists, starting at 0 until a non-empty list is found. Remove the first element and return it—the for- loop induces the O(k) worst case complexity. E.g., removeMin() – for i  0 to k+1 List L  A[i] – if( L.empty() = false ) v  L.remove-head() /*Removes list's head and returns it dequeue*/ return v – return NULL

Question 5 Give an O(nlog k) time algorithm to merge k sorted arrays A 1.. A k into one sorted array. n is the total number of elements (you may assume k≤n).

Question 5 Give an O(nlog k) time algorithm to merge k sorted arrays A 1.. A k into one sorted array. n is the total number of elements (you may assume k≤n). Solution: We will use a min-heap of k triples of the form (d, i, A d [i]) for 1 ≤ d ≤ k, 1≤ i ≤ n. The heap will use an array B. First we build the heap with the first elements lists A 1...A k in O(k) time. In each step extract the minimal element of the heap and add it at the end of the output Array M. If the array that the element mentioned in step two came from is not empty, than remove its minimum and add it to our heap. for d  1 to k – B[d]  (d, 1, A d [1]) Build-Heap(B) /*By the order of A d [1] */ for j=1 to n – (d, i, x)  Extract-Min(B) – M[j]  x – if i < A d.length then Heap-Insert(B,(d, i+1, A d [i+1])) Worst case time analysis: – Build-Heap : O(k) – done 1 time – Extract-Min : O(log k) – done n times – Heap-Insert : O(log k) – done n times – Total: O(nlogk)

Lempel-Ziv

Heaps דוגמה : הוסיפו את 9 בצעו Extract-min

Question 2 נתחו את זמני הריצה של מציאת i האיברים הקטנים ביותר בקבוצה בגודל n, ע " י שימוש ב : –מיון –תור העדפות פתרון בעזרת מיון : –מיון המפתחות בעזרת אלגוריתם מיון שלוקח O(nlog n) זמן. –מציאת i המפתחות הקטנים ביותר בזמן O(i). –סה " כ : O(i+nlogn)=O(nlogn) פתרון בעזרת תור העדפות –בניית ערימת מינימום בזמן O(n) –מצבעים הוצאת המינימום i פעמים בזמן O(ilog n) –סה " כ : O(n+ilogn). הערה : n+ilogn = Θ(max(n,ilogn)) וכמובן ש n+ilogn = O(nlogn) ( ואף מהיר יותר אם i ≠ Θ(n))

Question 4 Solution : If n 1 ≥ n 2 : Add the keys of H 2 to the array of H 1 from index n 1 +1 to index n 1 +n – The resulting array represents a correct heap due to the following reasoning: – Number of leaves in H1 is l 1 If l 1 is even the number of internal nodes is l 1 -1 and there are 2l 1 "openings" for new leaves. If l 1 is odd then there are l 1 internal nodes and 2l 1 +1≥n 2 openings – All keys from H 2 are added as leaves due to the fact stated in formula (3). As all keys in H 1 are smaller than any key in H 2, the heap property still holds in the resulting array. If n 1 < n 2 : Build a new heap with all the elements in H 1 and H 2 in O(n 1 + n 2 ) = O(2n 2 )=O(n 2 ).