Docsity

Amortized Cost Analysis for Stack Operations - Prof. Randy Shull, Study notes of Algorithms and Programming

Partial preview of the text

Download Amortized Cost Analysis for Stack Operations - Prof. Randy Shull and more Study notes Algorithms and Programming in PDF only on Docsity!

Stack Operations*

*Each operation runs in O(1) time.

A

B

C

S

Push( S,D ) A

B

C

D

S

Pop( S ) A

B

C

S

MultiPop( S,k )

MultiPop( S, k ) while not Stack-Empty( S ) and k ≠ 0 do Pop( S ) k ← k-

A

B

C

D

S

MultiPop( S, 3) A

B

S

E

Worst-Case Time

  • In a sequence of n stack operations starting with an empty stack, what is the worst-case cost of a multiPop operation?
  • Worst-case cost of n stack operations?

A S

MultiPop( S,n )

S

A

A (^) ν

2 1

Amortized Cost*

*Aggregate Method: Each object can be popped at most once for each time it is pushed.

A

B

C

S Push( S,B )

A S S MultiPop( S,2 )

S Push( S,A )

A A

B

Push( S,C )

S S Push( S,B ) MultiPop( S,5 )

A

B

S

Potential Energy

  • Associate a potential energy with the data structure at

each stage.

c ^ i = ci + Φ( Di ) - Φ( Di-1 )

Amortized cost

Actual cost

Change in potential due to operation

Push( S,A )

Push( S,B )

Push( S,C )

MultiPop( S,2 )

Push( S,B )

MultiPop( S,5 ) EmptyStack

Total Amortized Cost

• Σ 1 ≤ i ≤ n ci = Σ 1 ≤ i ≤ n ( ci + Φ( Di ) - Φ( Di-1 ))

= cn + Φ( Dn ) - Φ( Dn-1 ) +

cn-1 +^ Φ( Dn-1 ) -^ Φ( Dn-2 ) +... +

c 1 +^ Φ( D 1 ) -^ Φ( D 0 )

= Σ 1 ≤ i ≤ n ci + (Φ( Dn ) -^ Φ( D 0 ))

  • Thus, if we define Φ so that Φ( Di ) ≥ Φ( D 0 )^ ≥^ 0 for all

i , the total amortized cost is an upper bound on the total

cost.

^

For Example

A

B

C

S

A S S S

A A

B

S S

A

B

S

Φ = size of S

0

Push( S,A )

Push( S,B )

Push( S,C )

MultiPop( S,2 )

Push( S,B )

EmptyStack MultiPop( S,5 )

1 2 3 1 2 0

Ripple Counter

3 2 1 0

Total Amortized Cost

  • Suppose the i th Increment operation resets ti bits, so ci ≤ ti +1. The number of one's in counter after i th operation is b (^) i ≤ bi -1 - ti + 1
  • The potential difference is Φ( Di )-Φ( D (^) i-1 ) = b (^) i - bi - ≤ ( bi-1 - ti + 1) - b (^) i - = 1 - ti.
  • The amortized cost is therefore ci = ci + Φ( Di ) - Φ( Di-1 ) ≤ ( ti +1) + (1 - ti .) = 2

^

Aggregate Method

Flips every call

Flips every fourth call

Flips every other call

3 2 1 0

...