10 · Computational Geometry

Graham's scan · click points · cross-product test decides every turn

load:

What you're watching

The algorithm runs in three visible phases:

  1. Pivot search — sweep through every point to find the bottom-most one (greatest screen y; ties broken by smallest x). That point is guaranteed on the hull.
  2. Polar sort — gray rays fan out from the pivot to every other point. The algorithm then sorts them by polar angle (counterclockwise, math sense). This is the O(n log n) step.
  3. Scan — walk the sorted list, pushing points onto a stack. Before each push, while the top two stack points and the candidate would make a non-CCW turn, the top is popped. Each candidate triggers a flashing dashed triangle: blue if it's kept (left turn), red if the top of stack is popped (right turn).
RECOMMENDED PRESET
"spiral · lots of pops": the scan starts pushing eagerly, then begins popping as later candidates reveal that earlier ones were inside the hull all along. It's the clearest demo of why the cross-product test matters — you can read off "left or right turn?" by eye.

Why the cross-product test?

Every step of Graham's scan reduces to one question: given three points O, A, B, does the path O → A → B turn left or right? The textbook approach — compute angles with atan2, compare them — is wrong twice over: it's slow (transcendental) and it accumulates floating-point error. The cross product

cross(O, A, B)  =  (Ax − Ox)(By − Oy) − (Ay − Oy)(Bx − Ox)

decides the turn direction with two multiplies and a subtract — and if the inputs are integers, the result is exact. Sign convention (in screen coords with y pointing down):

The same primitive doubles as the polar-angle comparator: if cross(pivot, A, B) < 0 then A is more CCW than B. No angles ever get computed.

Reading the panel

Complexity

Graham's scan is O(n log n) overall — but the O(n log n) comes entirely from the polar sort. The actual hull-construction sweep is O(n) amortised: each point is pushed at most once and popped at most once. The visualisation makes this concrete: the comparison counter ticks fast during sort, then slows to a crawl during scan even though the visualisation is doing more.

What I learned writing this

← Back to all algorithms