Amortized Analysis
Amortized Analysis
Amortized Analysis
What is amortized analysis?
Aggregate method
T(n) = upper bound on total cost of n operations
Amortized cost is T(n)/n
Some operations may cost more, a lot more, than
T(n)/n
If so, some operations must cost less
But the average cost over the sequence will never
exceed T(n)/n
Accounting method
Each operation pays a “fee” (cost of operation)
Overcharge some operations and store extra as
pre-payment for later operations
Amortized cost is (total of fees paid)/n
Must ensure bank account never negative,
otherwise fee was not high enough and bound
does not hold
Overpayment stored with specific objects in data
structure (e.g., nodes in a BST)
UMBC CMSC 341 Amortized
10/6/2008 Analysis 5
Three methods (cont.)
Potential method
Like accounting method
Overpayment stored as “potential energy” of
entire data structure (not specific objects)
Must ensure that potential energy never falls
below zero
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
Worst case
Flip k bits per increment
Do that n times to count to n
O(kn)
But, most of the time we don’t flip many bits
Total: 15
0 0 0 0 0 0 0 0 0 0
$0 $0 $0 $0 $0 $0 $0 $0 $0 $0
0 0 0 0 0 0 0 0 0 1
$0 $0 $0 $0 $0 $0 $0 $0 $0 $1
0 0 0 0 0 0 0 0 0 1
$0 $0 $0 $0 $0 $0 $0 $0 $0 $1
Flip A(0) to 0 and pay with the $1 that was there already
Flip A(1) to 1 and pay $1 for flip and leave $1 with that
bit (total fee of $2)
0 0 0 0 0 0 0 0 1 0
$0 $0 $0 $0 $0 $0 $0 $0 $1 $0
0 0 0 0 0 0 0 0 1 0
$0 $0 $0 $0 $0 $0 $0 $0 $1 $0
0 0 0 0 0 0 0 0 1 1
$0 $0 $0 $0 $0 $0 $0 $0 $1 $1
0 0 0 0 0 0 0 0 1 1
$0 $0 $0 $0 $0 $0 $0 $0 $1 $1
Flip A(0) and A(1) to 0 and pay with the $$ that were there already
Flip A(2) to 1 and pay $1 for flip and leave $1 with that bit (total fee
of $2)
0 0 0 0 0 0 0 1 0 0
$0 $0 $0 $0 $0 $0 $0 $1 $0 $0
… and so on
We “overpay” by $1 for flipping each 0 to 1
Use the extra $1 to pay for the cost of flipping
it back to a zero
Because a $2 fee for each increment ensures
that we have enough money stored to
complete that increment, amortized cost is $2
= O(1) per operation
rz r’x
z x
ry r’y
y D A y
rx r’z
x C B z
A B C D
A B B C
A B B C
A B C D
A B C D
z
x
A y z y
x D
A B C D
B C