Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 261 Skew Heaps. Same idea, different technique Start with the same heap order property, but ignore complete tree requirement Notice that order of left.

Similar presentations


Presentation on theme: "CS 261 Skew Heaps. Same idea, different technique Start with the same heap order property, but ignore complete tree requirement Notice that order of left."— Presentation transcript:

1 CS 261 Skew Heaps

2 Same idea, different technique Start with the same heap order property, but ignore complete tree requirement Notice that order of left and right children is unimportant Notice that both addition and remove are special cases of merge

3 Removal as Merge You remove the root, you are left with two child trees Merge to form the new heap void removeFirst () { assert (root != 0); root = merge(root.left, root.right); }

4 But addition as merge? Addition is the merge of –The existing heap and –A new heap that has only one element (the thing being added). Public void add (EleType newValue) { root = merge(root, new Node(newValue)); }

5 There must be a trick To merge, take smaller of the two Then swap the children, and recursively merge. The swapping is key, if things get unbalanced, it keeps them from staying so

6 Merge algorithm Node merge (Node left, Node right) if (left is null) return right if (right is null) return left if (left child value < right child value) { Node temp = left.left; left.left = merge(left.right, right) left.right = temp return left; } else { Node temp = right.right right.right = merge(right.left, left) right.left = temp return right }

7 Example, merge two trees

8 Next Step

9 Why Long Trees cannot stay so

10 In practice? Amortized O(log n), not guaranteed O(log n) as in the heap But in practice just as fast or faster Interesting how it starts from same idea, goes totally different direction


Download ppt "CS 261 Skew Heaps. Same idea, different technique Start with the same heap order property, but ignore complete tree requirement Notice that order of left."

Similar presentations


Ads by Google