Presentation is loading. Please wait.

Presentation is loading. Please wait.

תרגול 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).

Similar presentations


Presentation on theme: "תרגול 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)."— Presentation transcript:

1 תרגול 9 Heaps Lempel-Ziv

2 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

3 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))

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

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

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

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

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

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

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

11 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?

12 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 גדול מבנו הקטן – מבצעים החלפה קטן מבנו הקטן – מסיימים גדול מאביו – מסיימים

13 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)

14 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)

15 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?

16 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.

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

18 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))

19 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 )

20 Question 4

21 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.)

22 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)

23 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

24 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).

25 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)

26 Lempel-Ziv

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

28 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))

29 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 ).


Download ppt "תרגול 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)."

Similar presentations


Ads by Google