Aggregate
Aggregate
Stack operations
In our first example of the aggregate method, we analyze stacks that
have been augmented with a new operation., each of which takes O(1)
time:
POP(S) pops the top of stack S and returns the popped object.
Since each of these operations runs in O(1) time, let us consider the
cost of each to be 1. The total cost of a sequence
of n PUSH and POP operations is therefore n, and the actual running
time for n operations is therefore (n).
The situation becomes more interesting if we add the stack
operation MULTIPOP(S, k), which removes the k top objects of
stack S, or pops the entire stack if it contains less than k objects. In the
following pseudocode, the operation STACK-EMPTY returns TRUE if
there are no objects currently on the stack, and FALSE otherwise.
MULTIPOP(S,k)
1 while not STACK-EMPTY(S) and k 0
2 do POP(S)
3 k k - 1
example of MULTIPOP.
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
Stack operations
To illustrate the accounting method of amortized analysis, let us
return to the stack example. Recall that the actual costs of the
operations were
PUSH 1 ,
POP 1 ,
MULTIPOP min(k,s) ,
The amortized cost of each operation is therefore its actual cost plus
the increase in potential due to the operation. By equation (18.1), the
total amortized cost of the n operations is
Stack operations
To illustrate the potential method, we return once again to the
example of the stack operations PUSH, POP, and MULTIPOP. We
define the potential function on a stack to be the number of objects
in the stack. For the empty stack D0 with which we start, we have
(D0) = 0. Since the number of objects in the stack is never negative,
the stack Di that results after the ith operation has nonnegative
potential, and thus
(Di) 0 = (D0).
The amortized cost of each of the three operations is O(1), and thus
the total amortized cost of a sequence of n operations is O(n). Since
we have already argued that (Di) (D0), the total amortized cost
of n operations is an upper bound on the total actual cost. The worst-
case cost of n operations is therefore O(n).