4/18/2013 1
1
Amortized Analysis
Chapter 14
CPTR 318
Amortized Analysis
Amortized analysis averages the time
required to perform a sequence of operations
- n a data structure over all the operations
performed
An individual operation may itself be relatively
expensive, but its average cost (amortized cost) may be small
Some Simple Examples
Two simple applications which illustrate how
the principles of amortized analysis apply:
Augmented stack Binary counter
Augmented Stack
A normal stack with an additional operation: multipop()
push(x)—pushes element x onto the stack, as usual pop()—pops the top element off of the stack and
returns the popped element, as usual
multipop(k) pops the top k elements off of the stack
Returns a vector containing the popped elements Notice, cannot just adjust the top-of-stack pointer; each element
must be inserted into the result vector
Augmented Stack Implementation
template <typename T> class MultiStack { vector<T> stack; // Vector of elements int top; // Top of stack public: MultiStack(int capacity): stack(vector<T>(capacity)), top(-1) {} bool isEmpty() const { return top < 0; } int size() const { return top + 1; } void push(const T& newElement) { int size = stack.size(); if ( top < size - 1 ) { stack[++top] = newElement; } } T pop() { T result; if ( top >= 0 ) { result = stack[top--]; } return result; } vector<T> multipop(int k) { vector<T> result; while ( !isEmpty() && k != 0 ) { result.push_back(pop()); k--; } return result; } };
Analysis of Stack Operations
push(x)—O(1) pop()—O(1) multipop(k)—min(n, k), where n is
the size of the stack
worst case is O(n)