Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 6310 Advanced Data Structure Wei-Shian Wang

Similar presentations


Presentation on theme: "CS 6310 Advanced Data Structure Wei-Shian Wang"— Presentation transcript:

1 CS 6310 Advanced Data Structure Wei-Shian Wang
Heaps CS Advanced Data Structure Wei-Shian Wang

2 Also called priority queues
Support operations: insert, find_min, delete_min Min-heap and max-heap

3 5.1 Balanced Search Trees as Heaps

4 insert : O(log n) find_min : O(log n)  O(1) delete_min : O(log n)

5 Make find_min in O(1) Store the current minimum in a variable
Look up the new current minimum in O(log n) time when we perform the next delete_min

6 delete_min – O(1) Delete the object current_min->object
Move current_min to the next list position If current_min->key is now larger than the key in the root of the balanced tree, add the left subtree of the balanced search tree to the invalid nodes structure; take the right subtree as new search tree; and return the node of the old root to the free list Return several nodes from the invalid nodes structure to the free list

7

8 insert – O(log n) find_min – O(1)
Split the search tree at current_min->key, and add the lower tree to the invalid nodes structure Insert the new key in search tree If the key is below current_min->key, set current_min to the new key and object find_min – O(1) Return current_min->key and current_min->object

9 Theorem. The heap structure can be realized using a balanced search tree with lazy deletion in time O(log n) for insert and O(1) for find_min and delete_min operations if the heap contains n element.

10 5.4 Leftist Heaps

11 Leftist Heap Properties
Each node contains an additional field, the rank, which is defined by n->rank = 1 if n->left = NULL or n->right = NULL n->rank = 1 + Min(n->left->rank, n->right->rank) if n->left ≠ NULL and n->right ≠ NULL Heap is empty if root->rank = 0

12 Most nodes are on the left All the merging work is done on the right
Each node in a leftist heap has the shortest path on the left side is at least as long as that on the right side: n->left->rank ≧ n->right->rank If they are not both defined, then if one of them exists, it is the left one: n->left = NULL only if n->right = NULL Most nodes are on the left All the merging work is done on the right

13

14 insert O(log n)

15 delete_min and merge O(log n)

16 Theorem. The leftist heap structure supports the operation find_min in O(1) time and insert, merge, and delete_min in O(log n) time

17 Leftist Heap Visualization

18 Thank you !


Download ppt "CS 6310 Advanced Data Structure Wei-Shian Wang"

Similar presentations


Ads by Google