CSCE 411 Lecture 14
« previous | Wednesday, September 26, 2012 | next »
Amortized Analysis
- aggregate method: brute force
- accounting method: assign costs to each operation so it's easy to sum them up while still ensuring the result is accurate
potential method: more sophisticated version of the accounting methodnot covered here
Heap
storing a heap in an array:
100 |-- 19 | |-- 17 | | |-- 2 | | `-- 7 | `-- 3 `-- 36 |-- 25 `-- 1
Stored as
a = [ 100, 19, 36, 17, 3, 25, 1, 2, 7 ]
Assume is indexed from to For each array index , has children and
Adding Element
- Insert at end of tree (fill bottom row from the left)
- Compare inserted element with parent. If the added element is greater than parent, swap the two elements.
- Repeat previous step until added element is comparatively less than its parent or the element is at the root
Adding an element takes (worst-case) time, so adding elements would take
Removing Element
- Remove root element
- Replace root with last element from lowest level
- Compare new root with children and swap with largest child
- Repeat previous step until heap property is satisfied.
Removing an element takes (worst-case) time.
Bottom-Up Construction
Place elements in array, interpret as binary tree.
Look at subtrees at height (measured from lowest level). If these trees have been heapified, then subtrees at height can be heapified by sending their roots down.
Initially, trees at height 0 are all heapified
Analysis
For an array of length , the number of nodes at height is at most . The cost to heapify a tree at height if all subtrees have been heapified is
Aggregate Method
Show that a sequence of operations takes time.
The amortized time is .
Example
Pushing an element onto a stack takes time. Thus pushing elements takes time.
Amortized cost per operation is
Example
Incrementing a binary number: each place has to flip every th increment:
- bit 0 flips with every increment
- bit 1 flips every other increment
- bit 2 flips every 4th increment
- bit 3 flips every 8th increment
- bit flips every th increment
Total number of bit flips in increment operations is:
(See MATH 152 Chapter 10.2#Geometric Series→)
Therefore, the amortized time is .