GVSU CIS 263
Week 7 / Day 1
Leftovers:
- Red black tree
- iterator invalidation
Heaps
Max-Heap:
- Each node is greater than its children.
- Usually a binary tree, but not necessarily.
- Insert new node at leaf and “bubble up”
- Remove: Move last leaf up and bubble down with greatest child.
- Why greatest child?
- Can be used with a FIFO cache
- Min-Heap: Same thing with minimum at top.
Heap using array:
- Heap can implemented using an array.
- For nodes 0 - 4, draw table showing index of children
- What is the formula?
- Given a node x, what is formula for parent?
floor((x-1)/2)
- What is the benefit to this implementation?
- Less metadata (e.g., pointers)
- Can we implement a BST this way? Why or why not?
- Rotations wouldn’t be as simple as moving pointers.
- How can we use a Heap to sort?
- Insert items into a heap, then pull them out.
- What would the running time be?
- O(n log n). There would be n insertions, each taking time log n, followed by n removals, each taking time log n.
- Any short-cuts?
- Just take the array and pretend it’s a max heap. The leaf nodes are, by definition, fine. Only need n/2 operations to make a valid heap.
- Notice that this is n log n, but not recursive.
Priority Queue
- Put things in order such that the “most important” stays at the front.
- Typically implemented with a heap.
- What would be running time using a “regular” vector or list?
- What is the running time using a heap?
Use of priority queues in discrete event simulation
d-Heap:
- Heaps don’t have to be binary. Suppose each node has d children.
- What is the advantage of increasing d?
- Inserts are faster because the tree is shallower.
- What is the disadvantage?
- Deletes are slower because you have to look for the maximum of all d children.
- Unless d is a power of 2, the multiplication/division can be expensive.
- There is evidence that having 4 children improves performance overall.
Treap:
- BST with random secondary key.
- Add item to BST.
- Use secondaray key to percolate up; but, rotate instead of copy. You end up with a valid BST.