Amortized Analysis and Dynamic Arrays
Amortized Analysis and Dynamic Arrays
2
Amortized Analysis Example
A[m] A[m-1] ... A[3] A[2] A[1] A[0] cost
----------------------------------- ----
0 0 0 0 0 0
0 0 0 0 0 1 1
0 0 0 0 1 0 2
0 0 0 0 1 1 1
0 0 0 1 0 0 3
0 0 0 1 0 1 1
0 0 0 1 1 0 2
3
Binary Counter Question
A[m] A[m-1] ... A[3] A[2] A[1] A[0] cost
----------------------------------- ----
0 0 0 0 0 0
0 0 0 0 0 1 1
0 0 0 0 1 0 2
0 0 0 0 1 1 1
0 0 0 1 0 0 3
0 0 0 1 0 1 1
0 0 0 1 1 0 2
2
d
d
an
an
an
an
1
2
4
Binary Counter Analysis
A[m] A[m-1] ... A[3] A[2] A[1] A[0] cost
----------------------------------- ----
0 0 0 0 0 0
0 0 0 0 0 1 1
0 0 0 0 1 0 2
0 0 0 0 1 1 1
0 0 0 1 0 0 3
0 0 0 1 0 1 1
0 0 0 1 1 0 2
0 0 0 1 1 1 1
0 0 1 0 0 0 4
≤ 𝑁 ∙ σ∞ 1
𝑖=0 2𝑖
σ∞ 1
𝑖=0 2𝑖 = 2
• So the total work is 2N 6
Binary Counter Banker’s Method
A[m] A[m-1] ... A[3] A[2] A[1] A[0] amortized cost
----------------------------------- ----
0 0 0 0 0 0
0 0 0 0 0 1* 2
0 0 0 0 1* 0 2
0 0 0 0 1* 1* 2
0 0 0 1* 0 0 2
0 0 0 1* 0 1* 2
0 0 0 1* 1* 0 2
0 0 0 1* 1* 1* 2
0 0 1* 0 0 0 2
7
Stack with multi-pop
8
Dynamic Arrays
9
Dynamic Arrays
10
Dynamic Arrays Bankers Method
• Suppose we give each insert 3 tokens.
– 1st token pays for the insert itself.
– Remaining tokens stored with the item.
– Use the tokens in the full array to pay for the copy.
5 3
5 3 7 ** 9 **
5 3 7 9
11
Tokens Question
5 3 7 9 2 10 4
A. 10 and 4
B. 9,2,10 and 4 0% 0% 0% 0%
C. 2,10, and 4
4
4
d
d
nd
..
D. They got used to play
an
an
o.
a
yD
,
10
10
10
a
2,
2,
pl
9,
to
Donkey Kong
ed
us
t
go
ey
Th
12
Dynamic Arrays
5 3 7 9 2 10 4 1 8**
13
Dynamic Arrays Deletion
5 3 7 9 2 10
Delete 10
5 3 7 9 2 **
Delete 2
5 3 7 9 ** **
14
When to downsize?
A. 25%
B. 50% 0% 0% 0%
C. Just keep the money and
%
say we did it.
...
25
50
a nd
ey
on
em
th
ep
ke
st
Ju
15
Dynamic Arrays
5 3 7 9 ** ** ** **
25 % 25 %
Result:
5 3 7 9
16
Dynamic Arrays Summary
17