Search code examples
algorithmanalysis

Regarding binary counter amortized analysis


This is regarding amortized analysis of binary counter. All the entries in the Array start at 0 and at each step we will be simply incrementing the counter.

Here author is mentioning as below.

We are using a potential function that is equal to the number of 1-bits in the current count.

Question 1: What does above statement mean?

And other question i have is in the analysis it is mentioned as

n+(n/2)+(n/4)+--- is atmost 2n. how we got result as atmost 2n?

Thanks!


Solution

  • The costs for incrementing in this example are the number of bit-flips to execute.

    I.e. incrementing 3 (0b11) to 4 (0b100) has cost of 3 (all three positions flipped).

    Now with that you couldn't say, that the algorithm is amortized constant, because the amount of time depends on the number of bit-flips and thus varies on the number.

    To work around that one use the potential method on a sequence of increment operations starting with 0. The potential is now the number of bits that are 1.

    • φ(0) = 0
    • φ(1) = 1
    • φ(2) = 1
    • φ(3) = 2
    • φ(4) = 1 etc

    This makes sense, since for each bit that is 1, an increment operation in the future will have to change it to 0 at some point. So whenever in increment occurs that needs to flip more than the last bit, it makes use of the potential of the value.

    Now continuing the amortized analysis, you will find, that the potential always increases by 1 and in each increment operation you decrease the potential for every 1 bit you flipped. Combining this in each operation you have costs of 2: a) flipping a 0 to a 1, b) saving 1 for the potential. Flipping all the ones before the 0 is paid using the potential.

    See also: http://en.wikipedia.org/wiki/Potential_method