CSCE 411 Lecture 14

From Notes
Jump to navigation Jump to search
Lecture Slides

« previous | Wednesday, September 26, 2012 | next »


Amortized Analysis

  1. aggregate method: brute force
  2. accounting method: assign costs to each operation so it's easy to sum them up while still ensuring the result is accurate
  3. potential method: more sophisticated version of the accounting method not 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

  1. Insert at end of tree (fill bottom row from the left)
  2. Compare inserted element with parent. If the added element is greater than parent, swap the two elements.
  3. 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

  1. Remove root element
  2. Replace root with last element from lowest level
  3. Compare new root with children and swap with largest child
  4. 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 .