Computational Geometry

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.

Wrap the points three ways

40

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

Which Pairs Touch?

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.

Count the pairs

Each grey line is one pair test. Drag the slider and watch the lines fill the space.

12

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.

The road

  1. The cross product: is a point left or right of a line?
  2. Segment crossing: four cross products decide it.
  3. The sweep line: test only segments that are neighbors.
  4. Graham scan: sort by angle, pop every right turn.
  5. Jarvis march: wrap the hull, cost n times h.
  6. Closest pair: split, solve each half, check a strip.
  7. Seven neighbors: why the strip check is cheap.
  8. Workbench: run the hull and the closest pair on your points.
  9. Beyond the chapter: Voronoi cells, float errors, point in polygon.
  10. Field guide: the numbers, the code, the credit.
You have 100 objects and test every pair. How many tests is that?

Chapter 1

Left or Right: The Cross Product

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.

Say it aloud

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.

d
d the cross product. Positive: p3 is left of the arrow p1 to p2. Negative: right. Zero: on its line.
x2 − x1
x-two minus x-one how far the first arrow moves across.
y3 − y1
y-three minus y-one how far the second arrow moves up.
y2 − y1
y-two minus y-one how far the first arrow moves up.
x3 − x1
x-three minus x-one how far the second arrow moves across.
In plain words

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.

With numbers

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 the third point across the line

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.

p1 = (0, 0), p2 = (6, 0), p3 = (3, 4). What is d, and which way is the turn?

Chapter 2

Do Two Segments Cross?

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.

Say it aloud

d-one times d-two is less than zero, and d-three times d-four is less than zero.

d1 · d2 < 0
d-one times d-two is below zero p1 and p2 are on opposite sides of the wall's line. A product is negative only when the signs differ.
and
and both tests must pass. One alone is not enough.
d3 · d4 < 0
d-three times d-four is below zero p3 and p4 are on opposite sides of the path's line.
In plain words

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.

With numbers

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 the endpoints

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.

Path (0, 0) to (4, 0) and wall (0, 2) to (4, 2) give d1 = −8 and d2 = −8. What follows?

Chapter 3

The Sweep Line: Check Only Neighbors

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).

Say it aloud

y of x equals y-one plus y-two minus y-one, times x minus x-one, over x-two minus x-one.

y(x)
y of x the height where the segment meets the sweep line at position x.
y1
y-one the height of the left endpoint.
y2 − y1
y-two minus y-one the total rise from left end to right end.
(x − x1) / (x2 − x1)
x minus x-one, over x-two minus x-one the fraction of the way along, from 0 at the left end to 1 at the right end.
In plain words

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).

With numbers

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:

  1. Sort the 2n endpoints by x. At equal x, left endpoints come first.
  2. At a left endpoint, insert the segment. Test it against its new neighbors above and below.
  3. At a right endpoint, test the neighbors above and below it against each other. Then delete it.
  4. Stop at the first test that finds a crossing.

Step the sweep

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.

Why does the sweep test two segments against each other when the segment between them is deleted?

Chapter 4

Convex Hull: Graham Scan

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:

  1. Take the lowest point as p0 (the leftmost of them on a tie). Sort the others by their angle around p0. Where several share one angle, keep only the farthest.
  2. Push p0 and the first two points on a stack. For each next point, look at the top two of the stack and the new point. While they make a right turn or a straight line (d ≤ 0), pop the top. Then push the new point.

Step the scan

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°.

  1. Stack A, B, H.
  2. C: the turn B, H, C has d = −4, a right turn. Pop H. The turn A, B, C has d = 16. Push C.
  3. D: B, C, D has d = 8. Push D.
  4. E: C, D, E has d = 4. Push E. The hull is A, B, C, D, E.

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.

Say it aloud

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.

A
A the area inside the polygon, in square grid units.
½
one half each term is twice a triangle's area, so halve the total.
Σi
the sum over i one term for each corner i, from 1 to n.
xi yi+1 − xi+1 yi
x-i times y-i-plus-one, minus x-i-plus-one times y-i the cross product of corner i and the next corner, seen from the origin.
In plain words

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.

With numbers

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.

In Graham scan, why pop the top of the stack on a right turn?

Chapter 5

Gift Wrapping: When the Hull Is Small

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.

Say it aloud

W is about n times h.

W
W the work: how many orientation tests Jarvis march makes.
≈
is about each scan skips one or two points, so the true count is a little lower.
n
n the number of input points. Each step scans all of them.
h
h the number of hull corners, one step for each.
In plain words

One step finds one corner and costs one scan of n points. There are h steps, so the work is n times h.

With numbers

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.

Change the shape of the cloud

Pick a shape and a point count. The bars count the real tests of each method on these points.

200

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.

10,000 points lie on a circle. About how many tests does Jarvis march make?

Chapter 6

Closest Pair: Divide and Conquer

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.

Say it aloud

dist equals the square root of x-two minus x-one squared, plus y-two minus y-one squared.

dist
dist the straight-line distance between the two points.
√
the square root of undoes the squaring, so dist is a length again.
(x2 − x1)2
x-two minus x-one, squared the across gap, squared.
(y2 − y1)2
y-two minus y-one, squared the up gap, squared.
In plain words

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.

With numbers

A (1, 2) and C (3, 1): the gaps are 2 and −1. dist = √(4 + 1) = √5 ≈ 2.236.

The method, as in CLRS:

  1. Sort the points by x. Draw a vertical line that puts half on each side.
  2. Solve each half the same way. With 3 points or fewer, check all pairs. Call the smaller of the two half answers δ (delta).
  3. A closer pair must have one point on each side, so both lie within δ of the line. Check only that strip, with its points sorted by y.

Step the split

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).

Say it aloud

T of n equals two T of n over two, plus c times n.

T(n)
T of n the steps needed to solve n points.
2 T(n/2)
two T of n over two solve the two halves, each with half the points.
c n
c times n split and check the strip: a fixed amount c per point. Chapter 7 shows why it is per point.
In plain words

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.

With numbers

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.

The left half's best is 3 and the right half's best is 5. Which points enter the strip?

Chapter 7

Why the Strip Is Cheap: Seven Neighbors

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.

Say it aloud

Delta over two, times root two, equals delta over root two, which is less than delta.

δ/2
delta over two the side of one small square.
· √2
times root two a square's diagonal is its side times about 1.414.
δ/√2
delta over root two the diagonal: the farthest apart two points in one square can be, about 0.707 δ.
< δ
is less than delta closer than the best distance found on that side.
In plain words

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.

With numbers

δ = 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.

Pack the box

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 δ.

Why can one δ/2 square on one side not hold two points?

Chapter 8

Workbench: Run It on Your Points

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.

Build a point 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:

  1. Press Random 30, then Hull. Count the corners. Most points are inside.
  2. Press Ring 24, then Hull. Every point is a corner. Graham scan does not care, but Jarvis march would make about 24 × 24 tests.
  3. Place a tight cluster of three points far from the rest, then press Closest pair. The answer is in the cluster, wherever the split falls.

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).

You place 24 points on a circle. What is h, the number of hull corners?

Chapter 9

Beyond the Chapter: Voronoi, Precision, Point in Polygon

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.

Grow the cells

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.

When floats lie

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.

Inside or outside?

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.

The points (0, 0), (0.1, 0.3), (0.3, 0.9) give d = 1.39 × 10−17 in floats. What is the truth?

Chapter 10

Field Guide

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.

ToolWhat it doesCostNumber to remember
Cross productSign gives left, right or collinear; half its size is triangle area.constant(0,0),(4,0),(4,3): +12
Segment crossingEach segment straddles the other, plus the on-segment test for zeros.constantX example: d = −16, 16, 16, −16
Sweep lineDoes any pair cross? Test only neighbors.n log nfound at event 4 of 8
Graham scanHull by angle sort and a stack.n log nA, B, C, D, E; area 18
Jarvis marchHull by wrapping, one corner per scan.n · h8 points, h = 5: 30 tests
Chan's algorithmMixes both.n log h1996
Closest pairSplit, solve halves, check the strip.n log nD, F at 2; δ was √5
Strip boundAt most 8 points in a δ by 2δ box.7 checks per pointdiagonal 0.707 δ
VoronoiNearest-site cells.n log n (Fortune)≤ 2n − 5 corners

Check before you trust a geometry routine

  1. Test the cross product on (0, 0), (4, 0), (4, 3): it must give +12. That fixes the sign and the y direction.
  2. Test the degenerate cases: three collinear points, a shared endpoint, two equal points.
  3. Compare with brute force on a few thousand random sets of up to 12 points.
  4. Use integers or exact fractions where you can.
  5. Time it at n and 2n. An n log n method should take a bit more than twice as long, not four times.

The core, in code

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.

The lower bound

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.

Keep going

The takeaway. Find the one primitive (the sign of a cross product). Then find the order (by x, by angle, by y) that lets you call it about n log n times instead of n2.
Which step sets the n log n cost of Graham scan?

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.

Credit and source

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.

CLRS Chapter 33: Computational Geometry
Introduction to Algorithms, third edition (MIT Press) · Back to Gleams