Every algorithm here asks one question many times: is this point left or right of that line? The art is to ask it fewer times. For 40 points, checking every pair as a hull edge asks 59,280 times. Graham scan asks a few hundred times.
Pick a method and press Wrap. Count the tests it makes on the same points. Then we build, piece by piece: the cross product, segment crossing, the sweep line, two hull algorithms and the closest pair.
You need coordinates on a grid, sorting and a little Python. Divide and conquer (CLRS Chapter 4) helps in Chapter 6. We build the rest from zero.
Based on Chapter 33 of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. The fourth edition dropped this chapter. Chapter 9 here goes past the book. The explanations, toys and devices are our own.
Random points. The counts are real: the page runs each method and counts every orientation test, plus the sort comparisons for Graham scan. Every pair checks each other point against each ordered pair, so it makes n(n − 1)(n − 2) tests.
Chapter 0
Count the pairs a brute-force check must test, and see why that count grows too fast
A game has 200 moving objects. Each frame, the engine must find the pairs that touch. The plain way is to test every pair. How many pairs is that?
Each of the n objects pairs with the n − 1 others, and that counts each pair twice. So there are n(n − 1)/2 pairs. For 200 objects that is 19,900 tests a frame. At 60 frames a second it is 1,194,000 tests a second.
Each grey line is one pair test. Drag the slider and watch the lines fill the space.
The pair count is exact. The n log2 n figure is an order of growth for a sweep, not an exact count.
Double the objects and the pairs grow four times. This is quadratic growth: the work grows with the square of the input. At a million points, n(n − 1)/2 is about 5 × 1011. A method that costs about n log2 n needs about 2 × 107 steps.
Computational geometry is the study of algorithms for points, segments and polygons. CLRS Chapter 33 covers four tools. All four rest on one test, the cross product, and all four use the shape of the data to skip most pairs.
The failure. Symptom: a collision check is fast in tests with 20 objects and stalls with 2,000. Measure: time it at n and at 2n; a quadratic method takes four times as long. Fix: sort the objects first, then test only the ones that are near in the sort.
Chapter 1
Drag a point across a line and watch one number change sign
You drive from point p1 to point p2. At p2 you must turn toward p3. Do you turn left or right? This is the orientation test, and every algorithm in this lesson calls it.
Write each point by its coordinates: p1 = (x1, y1), and so on, with y pointing up. Draw two arrows from p1: one to p2 and one to p3. Call the number that compares them d, the cross product of the two arrows.
d equals x-two minus x-one, times y-three minus y-one, minus y-two minus y-one, times x-three minus x-one.
Multiply the across-step of the first arrow by the up-step of the second. Subtract the up-step of the first times the across-step of the second. The sign of d is the turn; half of the size of d is the area of the triangle p1 p2 p3.
p1 = (0, 0), p2 = (4, 0), p3 = (4, 3). d = 4 × 3 − 0 × 4 = 12. It is positive, so the turn is left. The triangle has area 12/2 = 6, the same as half of base 4 times height 3.
Drag any of the three points. Purple fill means a left turn, pink means a right turn. The fill is the triangle; its area is half of d.
Points snap to whole grid units, so d is always a whole number.
Move p3 to (4, −3). Now d = 4 × (−3) − 0 × 4 = −12: a right turn. Move it to (8, 0). Then d = 4 × 0 − 0 × 8 = 0: the three points sit on one line, which is collinear.
The test has no division, no square root and no angle. With whole-number inputs it gives an exact answer. That is why CLRS builds the whole chapter on it.
The failure. Symptom: every turn comes out the wrong way round. Measure: test (0, 0), (4, 0), (4, 3); it must give +12. Fix: check that y points up. On a screen y points down, which flips every sign.
Chapter 2
Use four cross products to test if each segment straddles the other
A robot plans to move in a straight line from p1 to p2. A wall runs from p3 to p4. Does the path hit the wall? Each is a segment: the straight piece between two endpoints.
Two segments cross when each one straddles the line of the other: its two endpoints lie on opposite sides. The cross product tells the side. Call d1 and d2 the cross products of p1 and p2 against the arrow p3 to p4. Call d3 and d4 those of p3 and p4 against the arrow p1 to p2.
d-one times d-two is less than zero, and d-three times d-four is less than zero.
Find the side of each endpoint against the other segment, four cross products in all. If d1 and d2 have opposite signs, and d3 and d4 have opposite signs, the segments cross.
Path (1, 1) to (5, 5), wall (1, 5) to (5, 1). d1 = −16, d2 = 16, d3 = 16, d4 = −16. Both products are −256, so they cross, at (3, 3).
Drag any endpoint, or pick a case. Each endpoint shows its sign against the other segment.
Points snap to whole grid units, so every d is exact.
Why four tests and not two? Pick Line hit, segment miss: path (0, 0) to (4, 0), wall (6, −1) to (6, 1). The wall's ends straddle the path's line: d3 = −4, d4 = 4. But the path's ends are both on one side of the wall's line: d1 = 12, d2 = 4. The lines meet at (6, 0), past the end of the path.
A zero needs care. Pick Touching: wall (2, 0) to (2, 3) ends on the path. Then d3 = 0. The on-segment test then checks that (2, 0) lies inside the path's bounding box, x from 0 to 4 and y from 0 to 0. It does, so they touch.
The failure. Symptom: a T-shaped meeting or two overlapping collinear segments report no contact. Measure: test the Touching case. Fix: for each d that is 0, run the on-segment test on that endpoint.
Chapter 3
Slide a vertical line across the plane and test each segment only against the ones next to it
You have n segments and one question: do any two cross? Testing every pair costs n(n − 1)/2 tests. The sweep line does it in about n log n steps.
Picture a vertical line that slides from left to right. At each moment it cuts some segments, stacked from bottom to top. A segment enters the stack at its left endpoint and leaves at its right endpoint. These endpoints are the events. To order the stack at position x, compute where each segment is at that x. Call a segment's endpoints (x1, y1) and (x2, y2), and its height at x y(x).
y of x equals y-one plus y-two minus y-one, times x minus x-one, over x-two minus x-one.
Find what fraction of the way along the segment x is. Add that fraction of the rise to y1. Sort the segments on the sweep line by this y(x).
Segment c runs from (1.5, 4) to (5, 4.2). At x = 2 the fraction is 0.5/3.5 = 0.143, so y(2) = 4 + 0.2 × 0.143 = 4.03. Segment a, from (1, 1) to (9, 7), has y(2) = 1 + 6 × 1/8 = 1.75. So a sits below c.
The key fact: two segments that cross must be next to each other in the stack just before they cross. So the algorithm tests only neighbors:
Press Step. The blue line moves to the next event. Warm marks the pair under test. The box lists the stack from bottom to top.
Four made-up segments, checked with a script. a (1, 1) to (9, 7), c (1.5, 4) to (5, 4.2), b (2, 7) to (10, 2), d (6, 1) to (8, 1.5). Only a and b cross, at about (5.82, 4.61).
The trace. At x = 1 insert a. At 1.5 insert c above a; c and a do not cross. At 2 insert b on top; b and c do not cross. At 5, c ends. Its neighbors a and b become adjacent, so we test them: they cross. The algorithm stops after 4 of 8 events, before the sweep reaches the crossing at x = 5.82.
The stack is a balanced binary search tree, so each insert, delete and neighbor lookup costs about log n. With 2n events, the total is about n log n.
The failure. Symptom: the sweep misses a crossing that brute force finds. Measure: run it on this example; if it returns false, look at the delete step. Fix: at a right endpoint, test the two segments that become neighbors.
Chapter 4
Sort the points by angle, walk them with a stack, and pop every right turn
Stretch a rubber band around a set of nails and let it go. The shape it snaps to is the convex hull: the smallest convex polygon that holds every point. Walk around it counterclockwise and every turn is a left turn.
Graham scan (Ronald Graham, 1972) builds it in two phases:
Press Step. Warm is the point under test. A pink flash is a right turn: the top of the stack pops. Teal edges are the stack.
The first set is the hand example below. New points are random.
The hand example uses 8 points. A (0, 0), B (4, 0), C (4, 4), D (2, 5), E (0, 4), F (2, 2), G (1, 1), H (3, 1). The lowest point is A. By angle: B at 0°, H at 18.4°, then G, F and C all at 45°. Keep C, the farthest. Then D at 68.2° and E at 90°.
How big is the hull? Number the hull corners 1 to n in counterclockwise order and wrap back to 1 after n. The shoelace formula gives its area A from the corner coordinates.
A equals one half of the sum over i of x-i times y-i-plus-one, minus x-i-plus-one times y-i.
For each corner and the next one, multiply crosswise and subtract. Add up the n results and halve the total. Counterclockwise order gives a positive A.
Hull A, B, C, D, E: the terms are 0, 16, 12, 8 and 0. They add up to 36, so the area is 36/2 = 18. Check: the square below y = 4 has area 16, and the roof triangle has area 2.
The cost: the sort takes about n log n. In the stack phase the scan pushes each point once and pops it at most once, so that part is linear. A faster hull would give a faster sort, which is impossible for comparison sorts (Chapter 10 shows why).
The failure. Symptom: the hull has extra corners in the middle of straight edges, or it loops. Measure: run it on G, F, C, which share one angle. Fix: pop on d ≤ 0, not d < 0, and keep only the farthest point at each angle.
Chapter 5
Wrap a string around the points one corner at a time, and see when it beats sorting
Tie a string to the lowest point and pull it tight while you walk around the set. Each time the string meets a new point, that point is a hull corner. This is Jarvis march, also called gift wrapping.
Each step keeps one candidate and scans every other point. If a point lies to the right of the arrow from the current corner to the candidate, it becomes the new candidate. After one full scan the candidate is the next corner. Call the number of points n and the number of hull corners h. Call the total number of orientation tests W.
W is about n times h.
One step finds one corner and costs one scan of n points. There are h steps, so the work is n times h.
The 8 points of Chapter 4 have h = 5 corners. n · h = 40. Our code skips the current corner and the first candidate, so it makes 5 × 6 = 30 tests.
An algorithm whose cost depends on the size of its answer is output-sensitive. Graham scan costs about n log n whatever h is. Jarvis march wins when h is smaller than log n and loses when h is large.
Pick a shape and a point count. The bars count the real tests of each method on these points.
Random points. Graham's count includes its sort comparisons. In a square, h grows like log n; in a disk, faster; on a circle, every point is a corner.
Try Circle at 800 points. Every point is a corner, so h = n and Jarvis march makes about 640,000 tests. Graham scan stays near n log n. Chan's algorithm (1996) mixes the two and costs about n log h in every case.
The failure. Symptom: Jarvis march never stops. Measure: count the corners; if the count passes n, it is looping. Fix: when two candidates are collinear with the current corner, take the farther one, and stop when you return to the start.
Chapter 6
Split the points in half, solve each half, then check a thin strip across the cut
Air traffic control watches n planes. Which two are closest? Checking every pair costs n(n − 1)/2 distances. Divide and conquer does it in about n log n.
Call two points (x1, y1) and (x2, y2), and the straight-line length between them dist.
dist equals the square root of x-two minus x-one squared, plus y-two minus y-one squared.
Square the across gap and the up gap, add them, and take the square root. This is Pythagoras. To compare two distances, compare the sums and skip the root.
A (1, 2) and C (3, 1): the gaps are 2 and −1. dist = √(4 + 1) = √5 ≈ 2.236.
The method, as in CLRS:
Press Step: split, best on the left, best on the right, then the strip. Blue is the line and the strip.
The first set is the hand example below, checked against brute force. New points are random.
The hand example uses 8 points. A (1, 2), B (2, 8), C (3, 1), D (5, 6), E (6, 3), F (7, 6), G (8, 1), H (9, 5). Split at x = 5.5. The left best is A and C at √5; the right best is F and H at √5. So δ = √5 ≈ 2.236.
The strip holds x from 3.26 to 7.74: D, E and F. By y they are E (6, 3), D (5, 6), F (7, 6). E to D has a y gap of 3, more than δ, so stop. D to F is 2. The answer is D and F at distance 2. It crosses the line, so only the strip finds it.
How much work is that? Call the time for n points T(n).
T of n equals two T of n over two, plus c times n.
Each level of halving does about c · n work in all. Halving n down to 1 takes log2 n levels. So the total is about c · n log2 n, the same as merge sort.
For n = 8 there are log2 8 = 3 levels of 8 steps: about 24, against 28 pairs. For a million points: about 2 × 107 steps, against 5 × 1011 pairs.
The failure. Symptom: the result is right but takes n log2 n time. Measure: look for a sort inside the recursion. Fix: sort by y once at the start and split that list at each level, as CLRS does.
Chapter 7
Try to pack points into the strip and find that only eight fit
The strip could hold every point. Checking all pairs in it would bring back the quadratic cost. CLRS shows that each strip point needs at most 7 checks.
Take a point p in the strip. Any partner closer than δ lies above it by less than δ. So it sits in a box δ tall and 2δ wide, centred on the line. Cut the box into 8 squares, each δ/2 on a side: 4 on the left of the line and 4 on the right.
Two points in one square would be on the same side. Their distance is at most the square's diagonal.
Delta over two, times root two, equals delta over root two, which is less than delta.
Two points in one square would be closer than δ and on the same side. But δ is the closest distance on each side. So each square holds at most one point, and the box holds at most 8: p and 7 others.
δ = 2. Each square is 1 by 1, with diagonal 1.414. Two points in one square would be 1.414 apart, closer than 2 on the same side. That cannot happen.
Tap inside the box to place a point. The box refuses a point closer than δ to another on its own side. How many can you fit?
Points on the line count as left. Show 8 places one point at each corner of each half; corners are exactly δ apart, and the rule allows that.
So the scan is short. Sort the strip by y. For each point, compare it with the next points in y order and stop when the y gap reaches δ, or after 7 points. Each strip point costs a fixed amount, so the strip costs c · n.
The failure. Symptom: the strip loop runs for a long time on dense data. Measure: count comparisons per strip point; more than 7 means the stop rule is missing. Fix: break when the y gap reaches δ.
Chapter 8
Place points, run the hull and the closest pair, and count the tests against brute force
Now run both algorithms on your own points. Tap to add a point. The read-out compares each algorithm's tests with brute force on the same set.
Tap the canvas to add points. Then press Hull or Closest pair.
Counts are real. Hull: Graham scan tests and sort comparisons against every-pair's n(n − 1)(n − 2). Closest pair: distance checks of divide and conquer against n(n − 1)/2.
Three things to try:
At 30 points the savings look small: brute force for the closest pair needs 435 checks. They grow fast. At 3,000 points brute force needs about 4.5 million checks, and divide and conquer needs about 35,000 steps.
The failure. Symptom: the hull or the closest pair is wrong only when you place points by hand. Measure: place three points in a row, or two on the same spot. Fix: handle collinear points (pop on d ≤ 0) and equal points (distance 0 is a valid answer).
Chapter 9
Split the plane by nearest site, see a float get a sign wrong, and test if a point is inside
A city has 8 fire stations. For each street corner, which station is nearest? Give each station the set of places closer to it than to any other. These sets are Voronoi cells, and together they form the Voronoi diagram. CLRS does not cover it; it is the next step after the closest pair.
Tap to add a site. Each shade is the region nearest one site. Turn on Delaunay to join sites whose cells touch.
The page finds the cells pixel by pixel, by brute force, for the picture only. It finds Delaunay triangles by testing every triple for an empty circle, which is fine up to 30 sites.
The border between two cells lies on the perpendicular bisector of the two sites. Each cell is convex. With n sites there are at most 2n − 5 corners and 3n − 6 edges, so the diagram stays linear in size. Fortune's sweep (1987) builds it in about n log n. Join two sites when their cells share an edge and you get the Delaunay triangulation: no site lies inside any triangle's circumcircle.
The cross product is exact for whole numbers. With floats it can get the sign wrong. Take (0, 0), (0.1, 0.3) and (0.3, 0.9). They lie on one line, so d should be 0. In double precision, d = 1.39 × 10−17: a left turn that is not there. A hull built from such tests can gain or lose a corner.
The failure. Symptom: a hull or a crossing test flips when you move a point by 10−15. Measure: repeat the test with exact fractions (Python's fractions.Fraction). Fix: use integer coordinates, or exact predicates that fall back to exact arithmetic when d is near zero.
To test if a point is inside a polygon, cast a ray to the right and count how many edges it crosses. An odd count means inside. Each edge test is one comparison and one division, or one cross product. The cost is linear in the number of edges.
Chapter 10
Keep the terms, the numbers, the code and the checks in one place
One test, the sign of a cross product, answers left or right. Segment crossing uses four of them. The sweep line, Graham scan and the closest pair all sort first, then make a near-linear number of tests. That is how they reach about n log n.
| Tool | What it does | Cost | Number to remember |
|---|---|---|---|
| Cross product | Sign gives left, right or collinear; half its size is triangle area. | constant | (0,0),(4,0),(4,3): +12 |
| Segment crossing | Each segment straddles the other, plus the on-segment test for zeros. | constant | X example: d = −16, 16, 16, −16 |
| Sweep line | Does any pair cross? Test only neighbors. | n log n | found at event 4 of 8 |
| Graham scan | Hull by angle sort and a stack. | n log n | A, B, C, D, E; area 18 |
| Jarvis march | Hull by wrapping, one corner per scan. | n · h | 8 points, h = 5: 30 tests |
| Chan's algorithm | Mixes both. | n log h | 1996 |
| Closest pair | Split, solve halves, check the strip. | n log n | D, F at 2; δ was √5 |
| Strip bound | At most 8 points in a δ by 2δ box. | 7 checks per point | diagonal 0.707 δ |
| Voronoi | Nearest-site cells. | n log n (Fortune) | ≤ 2n − 5 corners |
pythonfrom math import dist, inf def cross(o, a, b): # > 0: o, a, b turn left return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0]) def on_segment(p, q, r): # q collinear with p, r: inside their box? return min(p[0],r[0]) <= q[0] <= max(p[0],r[0]) and min(p[1],r[1]) <= q[1] <= max(p[1],r[1]) def segments_cross(p1, p2, p3, p4): d1, d2 = cross(p3, p4, p1), cross(p3, p4, p2) d3, d4 = cross(p1, p2, p3), cross(p1, p2, p4) if ((d1 > 0) != (d2 > 0)) and d1 and d2 and ((d3 > 0) != (d4 > 0)) and d3 and d4: return True # each straddles the other return ((d1 == 0 and on_segment(p3, p1, p4)) or (d2 == 0 and on_segment(p3, p2, p4)) or (d3 == 0 and on_segment(p1, p3, p2)) or (d4 == 0 and on_segment(p1, p4, p2))) def convex_hull(pts): # monotone chain: Graham scan sorted by x, not angle pts = sorted(set(pts)) if len(pts) < 3: return pts def chain(seq): st = [] for p in seq: while len(st) >= 2 and cross(st[-2], st[-1], p) <= 0: st.pop() # right turn or straight: inside st.append(p) return st[:-1] return chain(pts) + chain(reversed(pts)) # counterclockwise def closest_pair(pts): # returns (distance, p, q) def solve(px): # px: points sorted by x n = len(px) if n <= 3: return min(((dist(a, b), a, b) for i, a in enumerate(px) for b in px[i+1:]), default=(inf, None, None)) mid = n // 2; x0 = px[mid][0] best = min(solve(px[:mid]), solve(px[mid:])) strip = sorted((p for p in px if abs(p[0] - x0) < best[0]), key=lambda p: p[1]) for i, a in enumerate(strip): for b in strip[i+1:i+8]: # at most 7 neighbors if b[1] - a[1] >= best[0]: break best = min(best, (dist(a, b), a, b)) return best return solve(sorted(pts))
The strip here is re-sorted at each level, which costs n log2 n. CLRS passes a y-sorted list down instead to reach n log n.
Why not faster than n log n? Take numbers x1 to xn and make the points (xi, xi2). They all lie on the curve y = x2, so all are hull corners. Read the hull in order and the numbers come out sorted. A hull method faster than n log n would sort faster than any comparison sort can.
Now press Present or Teach and explain from memory. Say what the sign of the cross product means, why segment crossing needs four of them, and why the sweep tests neighbors at a delete. Trace Graham scan on A to H. Say why the closest pair needs the strip and why the strip costs 7 checks a point. Then go back to the hull and say which chapter explains each count.
This lesson re-teaches Chapter 33, Computational Geometry, of Introduction to Algorithms (third edition) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press, 2009). Ronald Graham published Graham scan in 1972 and R. A. Jarvis the march in 1973. Shamos and Hoey gave the sweep test in 1976, and Steven Fortune his Voronoi sweep in 1987. The text, toys and devices here are our own.