Imagine hammering nails into a board and stretching a rubber band around them all. When you let go, the band snaps into the tightest shape that contains every nail. That shape is the convex hull. Finding it is a basic problem in computational geometry, with uses in mapping, robotics, game collision checks and image processing. This lesson first introduces the one tool most geometry code relies on, the cross product, then builds the hull with Andrew’s monotone chain algorithm in O(n log n).
In this lesson you will learn
- Using the cross product to tell left turns from right turns
- The shoelace formula for polygon area
- Andrew’s monotone chain algorithm
- Building the lower and upper hulls with a stack
- Handling points that lie on a straight line
You should know stacks, qsort in C and structures.
Turns and Areas with the Cross Product
#include <stdio.h>
typedef struct { long x, y; } Point;
/* Cross product of (b - a) and (c - a):
> 0 c is to the LEFT of the line a->b (counter-clockwise turn)
< 0 c is to the RIGHT (clockwise turn)
= 0 a, b and c lie on one straight line */
long cross(Point a, Point b, Point c) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
const char *turn(long v) { return v > 0 ? "left turn" : v < 0 ? "right turn" : "straight"; }
int main(void) {
Point a = {0, 0}, b = {4, 0};
Point tests[] = { {2, 3}, {2, -3}, {8, 0} };
for (int i = 0; i < 3; i++) {
long v = cross(a, b, tests[i]);
printf("A(0,0) -> B(4,0) -> (%ld,%ld): cross = %3ld, %s\n",
tests[i].x, tests[i].y, v, turn(v));
}
/* Twice the area of a polygon (the shoelace formula uses the same idea) */
Point poly[] = { {0, 0}, {6, 0}, {6, 4}, {3, 7}, {0, 4} };
long twice = 0;
for (int i = 0; i < 5; i++) {
Point p = poly[i], q = poly[(i + 1) % 5];
twice += p.x * q.y - q.x * p.y;
}
printf("area of the house-shaped polygon: %.1f\n", twice / 2.0);
return 0;
}
Output
A(0,0) -> B(4,0) -> (2,3): cross = 12, left turn
A(0,0) -> B(4,0) -> (2,-3): cross = -12, right turn
A(0,0) -> B(4,0) -> (8,0): cross = 0, straight
area of the house-shaped polygon: 33.0
- For points A, B and C,
cross(a, b, c)tells which way you turn when walking from A to B and then on to C. - A positive value is a left turn (counter-clockwise), negative is a right turn (clockwise), and zero means the three points lie on one line.
- The size of the value is twice the area of triangle ABC. For A(0,0), B(4,0), C(2,3), the triangle’s area is 6, so the cross product is 12.
- The shoelace formula adds up
xi × yi+1 - xi+1 × yiaround a polygon to get twice its area. The house shape is a 6 × 4 rectangle (24) plus a roof triangle (9), which gives 33. - Using whole numbers (
long) avoids rounding errors, which matter a lot in geometry.
Andrew’s Monotone Chain
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { long x, y; } Point;
long cross(Point a, Point b, Point c) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
}
static int cmp(const void *p, const void *q) {
const Point *a = p, *b = q;
if (a->x != b->x) return (a->x > b->x) - (a->x < b->x);
return (a->y > b->y) - (a->y < b->y);
}
/* Andrew's monotone chain: O(n log n) because of the sort.
Build the lower hull left to right and the upper hull right to left,
popping any point that would make a right (clockwise) turn. */
int convexHull(Point *p, int n, Point *h) {
qsort(p, n, sizeof *p, cmp);
int k = 0;
for (int i = 0; i < n; i++) { /* lower hull */
while (k >= 2 && cross(h[k - 2], h[k - 1], p[i]) <= 0) k--;
h[k++] = p[i];
}
for (int i = n - 2, lower = k + 1; i >= 0; i--) { /* upper hull */
while (k >= lower && cross(h[k - 2], h[k - 1], p[i]) <= 0) k--;
h[k++] = p[i];
}
return k - 1; /* last point repeats the first */
}
int main(void) {
/* Positions of mobile towers; which ones form the outer fence? */
Point p[] = { {1, 1}, {4, 0}, {7, 2}, {6, 6}, {3, 7}, {0, 4},
{3, 3}, {5, 3}, {2, 5}, {4, 5}, {2, 2}, {6, 4} };
int n = sizeof p / sizeof p[0];
Point h[2 * 12];
int m = convexHull(p, n, h);
printf("Hull has %d of %d points (counter-clockwise):\n", m, n);
double perim = 0, twiceArea = 0;
for (int i = 0; i < m; i++) {
Point a = h[i], b = h[(i + 1) % m];
printf("(%ld,%ld) ", a.x, a.y);
double dx = (double)(b.x - a.x), dy = (double)(b.y - a.y);
perim += sqrt(dx * dx + dy * dy);
twiceArea += (double)(a.x * b.y - b.x * a.y);
}
printf("\nperimeter (fence length): %.2f\narea inside: %.1f\n", perim, twiceArea / 2);
return 0;
}
Output
Hull has 6 of 12 points (counter-clockwise):
(0,4) (1,1) (4,0) (7,2) (6,6) (3,7)
perimeter (fence length): 21.46
area inside: 33.0
- First, sort the points by x (and by y when x is equal).
- Lower hull: go left to right, keeping the hull points on a stack. Before adding a point, pop the top while the last two hull points and the new point make a right turn or are in a straight line (
cross <= 0). Those popped points are inside the hull. - Upper hull: do the same from right to left.
lowermakes sure the lower hull is never popped. - The last point added repeats the first one, so the function returns
k - 1. - Six of the twelve towers form the fence. The other six are inside it. The perimeter is the fence length, and the shoelace formula gives the area.
- Each point is pushed and popped at most once per pass, so building the hull is O(n). Sorting makes the whole algorithm O(n log n).
| Algorithm | Time | Notes |
|---|---|---|
| Check every pair as an edge | O(n3) | Easy to understand, very slow |
| Gift wrapping (Jarvis march) | O(n × h) | Fast when the hull has few points (h) |
| Graham scan | O(n log n) | Sorts points by angle around the lowest point |
| Andrew’s monotone chain | O(n log n) | Sorts by x; simple and avoids angles |
Common Mistakes
- Using
floatordoublefor coordinates when whole numbers would do, which brings rounding errors into the turn test. - Getting the sign of the cross product backwards, which builds a hull of the inner points or a twisted shape.
- Not deciding about collinear points:
<= 0drops points in the middle of an edge,< 0keeps them. - Overflow when coordinates are large: the products need 64-bit integers.
Practice Exercises
Exercise 1. Is the point (3, 3) to the left or right of the line from (0, 0) to (6, 2)?
Show answer
cross = (6 – 0) × (3 – 0) – (2 – 0) × (3 – 0) = 18 – 6 = 12. It is positive, so the point is to the left.
Exercise 2. Write a function that checks whether a point is strictly inside a convex polygon listed counter-clockwise.
Show answer
int insideConvex(const Point *h, int m, Point q) {
for (int i = 0; i < m; i++)
if (cross(h[i], h[(i + 1) % m], q) <= 0) return 0; /* not left of an edge */
return 1;
}
A point is inside a counter-clockwise convex polygon when it is to the left of every edge.
Frequently Asked Questions
What does “convex” mean?
A shape is convex if the straight line between any two points inside it stays inside it. A circle and a square are convex; a star or a crescent is not.
Where is the convex hull used in practice?
Games check collisions against simple convex shapes. Map software draws the area covered by a set of locations. Robots plan around obstacles using their hulls, and it is a first step in many other geometry algorithms, such as finding the two points furthest apart.
Summary
- The cross product tells left turns, right turns and straight lines apart, and gives areas.
- The shoelace formula finds the area of any simple polygon.
- Andrew’s monotone chain sorts the points, then builds the lower and upper hulls with a stack.
- The whole algorithm runs in O(n log n), using only whole-number arithmetic.
Back to the start of the series: Learn DSA in C.
