=
=
1
0
2 ] [
k
i
i
i A x
k-bit Binary Counter
Ctr A[4] A[3] A[2] A[1] A[0]
0 0 0 0 0 0
1 0 0 0 0 1
2 0 0 0 1 0
3 0 0 0 1 1
4 0 0 1 0 0
5 0 0 1 0 1
6 0 0 1 1 0
7 0 0 1 1 1
8 0 1 0 0 0
9 0 1 0 0 1
10 0 1 0 1 0
11 0 1 0 1 1
INCREMENT(A)
1. i 0
2. while i < length[A]
and A[i] = 1
3. do A[i] 0
4. i i + 1
5. if i < length[A]
6. then A[i] 1
k-bit Binary Counter
Ctr A[4] A[3] A[2] A[1] A[0] Cost
0 0 0 0 0 0 0
1 0 0 0 0 1 1
2 0 0 0 1 0 3
3 0 0 0 1 1 4
4 0 0 1 0 0 7
5 0 0 1 0 1 8
6 0 0 1 1 0 10
7 0 0 1 1 1 11
8 0 1 0 0 0 15
9 0 1 0 0 1 16
10 0 1 0 1 0 18
11 0 1 0 1 1 19
INCREMENT(A)
1. i 0
2. while i < length[A]
and A[i] = 1
3. do A[i] 0
4. i i + 1
5. if i < length[A]
6. then A[i] 1
The running cost for
flipping bits
INCREMENT(A)
1. i 0
2. while i < length[A] and A[i] = 1
3. do A[i] 0
4. i i + 1
5. if i < length[A]
6. then A[i] 1
Worst-case analysis
Consider a sequence of n insertions.
The worst-case time to execute one
insertion is O(k). Therefore, the worst-
case time for n insertions is n O(k) =
O(n k).
WRONG! In fact, the worst-case cost
for n insertions is only O(n) O(n k).
Lets see why.
Note: Youll be correct
If youd said O(n k).
But, its an overestimate.
Tighter analysis
Ctr A[4] A[3] A[2] A[1] A[0] Cost
0 0 0 0 0 0 0
1 0 0 0 0 1 1
2 0 0 0 1 0 3
3 0 0 0 1 1 4
4 0 0 1 0 0 7
5 0 0 1 0 1 8
6 0 0 1 1 0 10
7 0 0 1 1 1 11
8 0 1 0 0 0 15
9 0 1 0 0 1 16
10 0 1 0 1 0 18
11 0 1 0 1 1 19
A[0] flipped every op n
A[1] flipped every 2 ops
n/2
A[2] flipped every 4 ops
n/2
2
A[3] flipped every 8 ops
n/2
3
A[i] flipped every 2
i
ops
n/2
i
Total cost of n operations
i k never 0
Tighter analysis (continued)
) (
2
2 / 1 1
1
2
1
2
0
1
0
n O
n n n
n
i
i
k
i
i
=
=
|
.
|
\
|
= <
(
=
Cost of n increments
Thus, the average cost of each increment
operation is O(n)/n = O(1).
Accounting method
5/28/2012 Jurusan Teknik Informatika FTIF ITS 17
Assign different charges to different operations.
Some are charged more than actual cost.
Some are charged less.
Amortized cost = amount we charge.
When amortized cost > actual cost, store the
difference on specific objects in the data structure as
credit.
Use credit later to pay for operations whose actual
cost > amortized cost.
Differs from aggregate analysis:
In the accounting method, different operations can have
different costs.
In aggregate analysis, all operations have same cost.
Accounting method
5/28/2012 Jurusan Teknik Informatika FTIF ITS 18
Need credit to never go negative.
Otherwise, have a sequence of operations for which the
amortized cost is not an upper bound on actual cost.
Amortized cost would tell us nothing.
Let c
i
= actual cost of ith operation ,
= amortized cost of ith operation .
.
i
c
= =
s
n
i
i
n
i
i
c c
1 1