wild-inter.net

Resizable arrays  ·  the doubling trick, amortized

A stack on an array of fixed capacity C, kept between a quarter full and full: push on a full array copies everything into an array of twice the size; when it is only a quarter full, the next operation copies into an array of half the size. A single operation can cost Θ(n), but a copy is always preceded by many cheap operations that pay for it. The potential Φ — the distance of n to the nearer boundary, drawn as the blue bar — makes this precise.

Small screen: the arrays scroll sideways. The code and the analysis are below the drawing.
Detail
Push n, pop n
Leave the field empty for a random key. New operations are added right after the one on screen.
— / — Delay 650ms
The array zoom100%
written copied deleted potential Φ: distance from n to ¼C or C
Cost per operation
What happens
Popped
Amortized analysis
Java code
Input
A sequence of stack operations in the format of Sedgewick & Wayne’s tobe.txt: every word is pushed, a - pops. An optional first line init: a b c gives elements that are on the stack at the start; the initial capacity is the smallest power of two ≥ max(8, their number). Keys are up to 4 characters; # starts a comment. The stack holds at most 500 elements here. The array has capacity 8 at the start.