Gift Wrapping Algorithm — Definition, Formula & Example
The gift wrapping algorithm, also called the Jarvis march, finds the convex hull of a set of points. It starts at an outermost point and repeatedly swings a line around the set until the line touches the next point, as if wrapping paper around the points.
Let be a finite set of points in the plane. Let be the point with the least -coordinate, with ties broken by the least -coordinate. Given the current hull vertex , choose so that no point of lies strictly to the right of the directed line . If several points qualify, take the farthest one from . Stop when . The sequence lists the hull vertices counterclockwise. The algorithm runs in time, where is the number of hull vertices, so the worst case is .
Key Formula
Where:
- = The current hull vertex
- = The current candidate for the next hull vertex
- = Any other point being tested
- = Positive if r is left of the line from p to q, negative if r is right of it, and 0 if the three points are collinear
Worked Example
Problem: The points are A(0, 0), B(6, 2), C(4, 1), D(3, 5), E(1, 3), and F(3, 2). Use the gift wrapping algorithm to find the starting vertex and the hull vertex that comes after it, going counterclockwise.
Step 1: Find the starting point. A has the least x-coordinate and it is the only point with that value, so A is a hull vertex.
Step 2: Pick any candidate, say B. Test C against the line A to B. The result is negative, so C lies to the right. That means B cannot be next, and C replaces B as the candidate.
Step 3: Test every other point against the new line A to C. Each result is positive, so no point lies to the right. C is confirmed as the next hull vertex.
Answer: The hull starts at A(0, 0), and its first edge goes from A to C(4, 1). If you repeat the process from each new vertex, you get the full hull A, C, B, D, E. The point F(3, 2) is inside the hull.
Why It Matters
Gift wrapping is a standard first convex hull algorithm in computational geometry and algorithms courses. Its cost depends on the size of the output, so it beats Graham scan's when the hull has fewer than about vertices. Convex hulls appear in collision detection for games and robotics and in GIS boundary mapping.
Common Mistakes
Mistake: Ignoring the case where the cross product equals 0, which means a tested point is collinear with the current edge.
Correction: If you keep the nearer collinear point, the hull can include extra points that sit in the middle of an edge. In some implementations, the loop never closes. When the cross product is 0, keep the point farther from .
