View on GitHub

csc263

Notes for CSC263 - Data Structures and Analysis

Back to index

Amortized Analysis

Given a data structure and some operations, let $T(n)$ be the sum of upper bounds on worst case runtimes for $n$ operations

Amortized cost is $T(n)/n$ (basically average)

Example - binary counter

Aggregate method

Using a bit array $A$, $k = \vert A\vert $,

def Increment(A):
    i = 0
    while i < |A| and A[i] == 1:
        A[i] = 0
        i = i + 1
    if i < |A|:
        A[i] = 1

Naively, the runtime for Increment(A) is $\in \mathcal O(k)$, so calling it $n$ times results in a total runtime of $T(n) \in \mathcal O(nk)$, so amortized cost is $nk/n = k$

However, using more careful aggregate analysis:

for $n$ increments:

\[\begin{align*} T(n) &= \sum_{i=0}^{k-1} \lfloor n/2^i \rfloor \\ &\leq \sum_{i=0}^{k-1} n/2^i \\ &\leq n \sum_{i=0}^{\infty} 2^{-i} \\ &= 2n \end{align*}\]

So the amortized cost is $2n/n = 2$

Accounting method

Define:

Idea: