Gift wrapping algorithm
The gift wrapping algorithm, also known as Jarvis's march, is a computational geometry algorithm designed to compute the convex hull of a finite set of points in the Euclidean plane by simulating the process of tightly wrapping a string around the outermost points of the set.[1] The gift-wrapping technique was first proposed by D. R. Chand and S. S. Kapur in 1970, with R. A. Jarvis independently introducing the 2D version in 1973.[2][1] The algorithm begins at the leftmost point (the one with the smallest x-coordinate) and iteratively identifies each subsequent hull vertex by selecting the point that forms the smallest counterclockwise angle with respect to the current edge, continuing until the starting point is revisited to close the hull.[1][3]
This output-sensitive approach constructs the convex hull as an ordered list of vertices in counterclockwise order, making it particularly intuitive for visualizing the boundary formation akin to gift wrapping or rubber band stretching around the points.[3] The algorithm's time complexity is O(nh), where n is the total number of input points and h is the number of vertices on the convex hull, with worst-case performance of O(n²) occurring when all points lie on the hull (h = n) and best-case O(n) when the hull is a simple polygon like a triangle (h = 3).[3] Although less efficient than more optimal algorithms like the Graham scan (O(n log n)) or Chan's algorithm (O(n log h)) for large inputs, its simplicity and ease of implementation have made it a foundational teaching tool in computational geometry, with applications in computer graphics, pattern recognition, and geographic information systems.[3][4]
Introduction
Definition and Purpose
The convex hull of a finite set of points S in the Euclidean plane is defined as the intersection of all half-planes containing S, representing the smallest convex set that encloses every point in S.[5] This structure forms a convex polygon whose vertices are a subset of the points in S, providing the tightest convex boundary around the set.[3]
The gift wrapping algorithm, also known as Jarvis's march, is an output-sensitive method for computing the convex hull of a set of n points in the plane by iteratively constructing the boundary polygon.[6] Introduced in 1973, it simulates the process of wrapping a taut string or gift paper around the points, starting from an extreme point and progressively identifying hull vertices to enclose the entire set.[6] Its output sensitivity means the computational effort scales with both the input size and the number of hull vertices, making it efficient when the hull is simple.[3]
The core purpose of the algorithm is to determine the vertices of the convex hull, enabling applications in geometric boundary detection, such as collision avoidance in robotics or shape approximation in computer graphics, where identifying the enclosing convex polygon simplifies further analysis of point distributions.[3] Intuitively, it begins at an initial hull point, like the leftmost point, and for each subsequent step, selects the next vertex as the point that forms the smallest counterclockwise angle with the current edge, thereby "wrapping" the boundary around the points without enclosing interior ones.[6] This angular selection ensures the resulting polygon is convex and minimal.[3]
Historical Background
The gift wrapping algorithm was first proposed by Ray A. Jarvis in 1973 as a method for identifying the convex hull of a finite set of points in the plane.[6] In his seminal paper, "On the Identification of the Convex Hull of a Finite Set of Points in the Plane," Jarvis presented the algorithm as an improvement over earlier brute-force techniques for solving the convex hull problem, which aims to find the smallest convex polygon enclosing a set of points.[6]
This development occurred amid the emerging field of computational geometry in the 1970s, a period marked by growing interest in efficient geometric algorithms for computer graphics and pattern recognition. The algorithm's iterative approach, which selects successive points by finding the one that forms the smallest polar angle with the previous edge, offered a practical alternative to exhaustive searches, though its time complexity depends on the number of hull points.[6]
Commonly referred to as the Jarvis march in recognition of its creator, the name evokes the stepwise "wrapping" process around the point set, akin to encasing a gift with paper.[7] The algorithm gained further visibility through its inclusion in foundational texts, such as Franco P. Preparata and Michael I. Shamos's Computational Geometry: An Introduction (1985), where it was discussed as a key introductory example for convex hull computation.
Planar Algorithm
Step-by-Step Description
The gift wrapping algorithm, also known as Jarvis's march, computes the convex hull of a finite set of points in the plane by iteratively selecting successive vertices that form the boundary, analogous to wrapping a taut string around the points. The process begins with initialization by identifying an extreme point guaranteed to lie on the hull, specifically the point with the minimum x-coordinate; if multiple points share this x-coordinate, the one with the minimum y-coordinate is selected. This step requires scanning all points once and takes linear time.[1][3]
In the iteration phase, starting from the initial point as the current vertex p_0, the algorithm finds the next hull vertex by evaluating candidate points relative to p_0. For the first selection, it identifies the point q that forms the smallest polar angle with respect to the positive x-axis originating from p_0, using the orientation test (cross product) to compare angles without explicit trigonometric computation. For subsequent iterations, with previous vertex p_{i-1} and current p_i, the next point p_{i+1} is the one that minimizes the turning angle from the direction p_{i-1} p_i in the counterclockwise sense, again via orientation comparisons across all remaining points. This ensures the boundary is traced counterclockwise. To handle collinear points, which may tie in angle, the algorithm selects the farthest point from p_i among those forming the minimal angle, including only the extreme endpoints on the hull boundary while excluding intermediate collinear points.[1][3][8]
The iteration repeats, appending each new vertex to the hull list and updating the current point, until the algorithm returns to the initial point p_0, at which point the hull is closed and complete. This termination condition guarantees that all extreme points have been encircled without redundancy. The resulting output is an ordered list of hull vertices defining the convex polygon.[1][3]
As an illustrative walkthrough, consider a simple set of five points in the plane: A(0,0), B(4,0), C(2,3), D(1,1), and E(3,1). The leftmost point is A(0,0). From A, comparing polar angles to the positive x-axis, B(4,0) has angle 0°, E(3,1) about 18°, D(1,1) about 45°, and C(2,3) about 56°; thus, B is selected as the next vertex due to the smallest angle. Now from B, using the incoming direction from A to B (horizontal right), the turning angles are evaluated: C requires the smallest counterclockwise turn (about 124°), while D and E fall inside this angle; C is chosen. From C, the direction from B to C is checked against candidates, selecting A as it closes the minimal turn back to the start, skipping D and E as interior points. The hull is A-B-C-A, excluding D and E. If collinear points were present, say another point F(2,0) between A and B, the farthest (B) would be selected over F.[1]
Pseudocode Implementation
The pseudocode below implements the gift wrapping algorithm (Jarvis March) for computing the convex hull of a set of points in the plane. It takes as input a list of n 2D points and outputs an ordered list of the hull vertices in counterclockwise order starting from the leftmost point. The algorithm initializes with the point of minimum x-coordinate (breaking ties by minimum y-coordinate), then iteratively selects the next hull point by finding the one that forms the smallest polar angle with the current point, determined via the orientation test using the cross product.[3][9]
To support the angle comparison without computing explicit angles (which would require trigonometric functions), a helper function orientation(p, q, r) computes the sign of the cross product of vectors \overrightarrow{pq} and \overrightarrow{pr}:
\text{orientation}(p, q, r) = \text{sign} \left( (q_x - p_x)(r_y - p_y) - (q_y - p_y)(r_x - p_x) \right)
This returns 1 for counterclockwise (>0, left turn), 0 for collinear (=0), and -1 for clockwise (<0, right turn). A point i is selected as next if orientation(current, i, candidate) > 0 (i more counterclockwise than candidate).[3]
The implementation handles basic edge cases: for n = 0, returns an empty list; for n = 1, returns the single point; for n = 2, returns both points if distinct. Degenerate cases like all points collinear are handled by the orientation test, which selects the extreme endpoints as hull vertices while excluding interior collinear points (assuming strict inequality for turns; collinear points with cross product = 0 are not selected as "more counterclockwise").[9]
function JarvisMarch(points):
if points.size() == 0:
return []
if points.size() == 1:
return points
n = points.size()
// Find leftmost point (min x, then min y)
left = 0
for i = 1 to n-1:
if points[i].x < points[left].x or (points[i].x == points[left].x and points[i].y < points[left].y):
left = i
hull = []
p = left
do:
hull.append(points[p])
q = (p + 1) % n // Initial candidate
for i = 0 to n-1:
if i != p and (orientation(points[p], points[i], points[q]) > 0 or (orientation(points[p], points[i], points[q]) == 0 and distance(points[p], points[i]) > distance(points[p], points[q])):
q = i
p = q
while p != left
if hull.size() > 1 and hull[0] == hull[hull.size() - 1]: // Avoid duplicating start if n=2
hull.pop()
return hull
function orientation(p, q, r):
val = (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x)
if val == 0:
return 0
return 1 if val > 0 else -1 // 1 for CCW (>0), -1 for [CW](/page/CW) (<0)
function distance(p, q): // Euclidean distance squared for comparison
return (p.x - q.x)^2 + (p.y - q.y)^2
function JarvisMarch(points):
if points.size() == 0:
return []
if points.size() == 1:
return points
n = points.size()
// Find leftmost point (min x, then min y)
left = 0
for i = 1 to n-1:
if points[i].x < points[left].x or (points[i].x == points[left].x and points[i].y < points[left].y):
left = i
hull = []
p = left
do:
hull.append(points[p])
q = (p + 1) % n // Initial candidate
for i = 0 to n-1:
if i != p and (orientation(points[p], points[i], points[q]) > 0 or (orientation(points[p], points[i], points[q]) == 0 and distance(points[p], points[i]) > distance(points[p], points[q])):
q = i
p = q
while p != left
if hull.size() > 1 and hull[0] == hull[hull.size() - 1]: // Avoid duplicating start if n=2
hull.pop()
return hull
function orientation(p, q, r):
val = (q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x)
if val == 0:
return 0
return 1 if val > 0 else -1 // 1 for CCW (>0), -1 for [CW](/page/CW) (<0)
function distance(p, q): // Euclidean distance squared for comparison
return (p.x - q.x)^2 + (p.y - q.y)^2
This pseudocode assumes points are distinct and in general position where possible, but the collinear adjustment ensures robustness for degenerate inputs by favoring distant points on the same line.[3]
Time and Space Complexity
The gift wrapping algorithm, also known as Jarvis march, exhibits a time complexity of O(nh) in the planar case, where n is the number of input points and h is the number of vertices on the convex hull. This bound stems from the algorithm's iterative process, which starts at an extreme point (such as the leftmost) and proceeds by selecting the next hull vertex in each of h steps. In every iteration, the algorithm evaluates the polar angle (or equivalent orientation) relative to all n points to identify the one that forms the smallest angle, ensuring the boundary is traced counterclockwise.[6][10]
The derivation follows directly from this structure: each of the h iterations requires O(n) time to scan and compare angles across the point set, yielding a total of O(nh) operations. A simple recurrence captures this as T(n, h) = h \cdot O(n), assuming constant-time angle computations via cross products. In the worst case, h = \Theta(n) occurs when all points lie on the convex hull, such as in convex position, resulting in O(n^2) time. Conversely, the best case arises when h is small and constant, for instance h = 3 for points clustered inside a triangular hull, reducing the complexity to O(n).[6][10][11]
Regarding space complexity, the algorithm requires O(n) space to store the input point set throughout the process, along with O(h) additional space for the output hull vertices. Since h \leq n, the overall space usage remains linear in the input size.[12][10]
Comparisons to Other Methods
The gift wrapping algorithm marked a significant improvement over earlier brute-force methods for computing convex hulls in the plane, which required O(n³) time by exhaustively checking all triplets of points to identify hull edges. These 1970s brute-force approaches were computationally intensive even for modest input sizes, whereas gift wrapping achieves O(nh) time, where n is the number of points and h is the number of hull vertices, making it more efficient when h is small relative to n.[3]
Compared to Graham's scan, which runs in O(n log n) time in the worst case by sorting points by polar angle and performing a linear scan, gift wrapping is less efficient for large n due to its lack of logarithmic sorting but excels in output-sensitive scenarios where h ≪ n, such as when the hull is sparse. Graham's scan provides consistent performance across datasets by preprocessing all points, avoiding the per-hull-vertex scans that can degrade gift wrapping to O(n²) in the worst case when h ≈ n.[3]
Quickhull, a randomized incremental algorithm with expected O(n log n) time and worst-case O(n²), shares some adaptability to hull size through recursive partitioning but outperforms it in practice for moderate h by efficiently pruning interior points early, reducing the effective search space. While both are output-sensitive in expectation, Quickhull's divide-and-conquer strategy handles balanced distributions better, often completing in near-linear time for many real-world inputs, unlike gift wrapping's sequential wrapping that scales linearly with h.[3]
Chan's algorithm, proposed in 1996, achieves optimal O(n log h) time by hybridizing gift wrapping's local searches with a divide-and-conquer framework akin to Graham's scan, ensuring it is never asymptotically slower than either while being strictly faster when h is sublinear in n.[13] This combination leverages gift wrapping's edge-finding efficiency within smaller subproblems, making Chan's suitable for higher-dimensional extensions where pure gift wrapping becomes impractical.[3]
Overall, gift wrapping's primary trade-off lies in its simplicity, which facilitates teaching and implementation for small or sparse datasets, but it underperforms empirically for n > 1000 and h > log n, where O(n log n) methods like Graham's scan process inputs up to 10-100 times faster on uniform distributions.[14] For large-scale applications, its O(nh) bound renders it inefficient compared to adaptive algorithms like Quickhull or Chan's, though it remains valuable for conceptual clarity in computational geometry curricula.[3]
Extensions
Higher Dimensions
The gift wrapping algorithm generalizes to d-dimensional space by extending the iterative process of selecting extreme points to higher-dimensional facets. In d dimensions, the algorithm begins with an extreme point (such as the one minimizing a coordinate) and constructs the convex hull by successively identifying adjacent (d-1)-facets. From a current (d-1)-facet, the next vertex is found by evaluating all remaining points and selecting the one that minimizes the dihedral angle with the current facet, effectively "wrapping" the hull around the point set. This process continues until all facets are enumerated, ensuring the hull is closed. The orientation test to determine the minimizing point typically involves computing the signed volume of simplices or determinants of d \times d matrices for each candidate point.
In three dimensions, the algorithm adapts by wrapping around 2D faces via their boundary edges. Starting from an initial facet (e.g., a triangle formed by three extreme points), it processes each edge of the current face and identifies the next vertex as the point p that minimizes the dihedral angle between the current face and the new triangular face formed by the edge and p. This is equivalent to selecting p such that the supporting plane through the edge and p rotates the least from the current plane to exclude all other points. The process builds the polyhedral hull facet by facet, often using a breadth-first traversal to avoid duplicates, and terminates when the initial facet is revisited. For robustness, degenerate cases (e.g., coplanar points) are handled by perturbing points or using exact arithmetic.[15]
The time complexity in d dimensions is O(n f_d), where n is the number of points and f_d is the number of (d-1)-facets on the hull; by the upper bound theorem, f_d = O(n^{\lfloor d/2 \rfloor}) in the worst case, leading to O(n^{\lfloor d/2 \rfloor + 1}) overall. This bound arises because each of the f_d facets requires O(n) time to scan points and perform O(1) orientation tests per point (for fixed d), with the facet count growing combinatorially with dimension due to the structure of simplicial polytopes. In practice, the algorithm is output-sensitive and performs well when the hull size h (number of vertices) is small, but it degrades in high dimensions where enumerating facets becomes prohibitive.
Computing angles or orientations in high d poses significant challenges, as each test requires evaluating determinants of matrices up to size d, with arithmetic cost O(d^3) using Gaussian elimination, though specialized methods like lexicographic pivoting can reduce this for fixed d. The exponential growth in hull complexity (f_d) amplifies the per-facet cost, making the algorithm impractical for d > 5 without optimizations like hierarchical structures. Numerical instability from floating-point errors in determinant computations further necessitates robust variants, such as those using exact predicates.[15]
As a simple example, consider constructing the convex hull of four points forming a tetrahedron in 3D: start with the lowest point v_0, select two points v_1, v_2 to form the base edge with minimal polar angles, then find v_3 as the point maximizing the pyramid volume (or minimizing the dihedral angle from the base). Wrapping around the base edges confirms no further points and closes the hull with four triangular facets. This illustrates the algorithm's facet-by-facet growth in 3D.
Variants and Improvements
One notable variant integrates the gift wrapping algorithm as a subroutine within Chan's optimal output-sensitive convex hull algorithm, which achieves O(n log h) time complexity in the plane by partitioning the point set into subsets, computing initial hulls using an O(n log n) method like Graham scan on each, and then employing gift wrapping to merge hulls from small subsets of size roughly h, avoiding full scans in each step.[13]
Parallel versions of the gift wrapping algorithm distribute the search for the next hull vertex across multiple processors, particularly by parallelizing the angular sweep or extreme point queries in each wrapping step; for instance, a bulk-synchronous parallel (BSP) implementation on the plane enables efficient computation for large n by synchronizing angle evaluations, yielding near-linear speedup on p processors for balanced workloads.[7]
Addressing worst-case O(n²) behavior when h ≈ n, preprocessing techniques such as initial sorting by x-coordinate reduce redundant checks in starting point selection, while optimized angle searches using restricted areas—drawing from orienting curve methods—confine candidate evaluations to promising subsets, improving practical runtime to below O(nh) in numerical tests on random 2D and 3D points without altering the core O(nh) bound.[16]
Applications
Computational Geometry Uses
The gift wrapping algorithm serves as a foundational tool in computational geometry for hull-based queries, enabling efficient intersection detection between convex shapes by identifying boundary edges that facilitate separating axis tests without examining all points. It also supports proximity searches, such as nearest neighbor queries, by using the computed hull as a coarse filter to eliminate distant candidates and focus on boundary-adjacent points. In Voronoi diagram preprocessing, the algorithm's incremental edge-finding mechanism aids in constructing Delaunay triangulations, the dual of Voronoi diagrams, through specialized gift-wrapping steps that extend the planar hull computation to tetrahedralization in higher dimensions.[17][18]
Beyond direct queries, the gift wrapping algorithm integrates with other geometric primitives, including arrangements of lines and curves, where hulls of vertex sets define the convex boundaries of cells in the arrangement, aiding in topological analysis and zone computations. In motion planning, it contributes to defining free space by computing convex hulls of obstacle configurations or their Minkowski sums, which bound collision-free regions and simplify path optimization in robotic navigation.[17][19]
The algorithm's educational value lies in its intuitive, step-by-step process, which mirrors physical gift wrapping and provides a simple implementation for teaching output-sensitive algorithms in computational geometry courses, emphasizing how performance depends on the hull size rather than solely input scale.[3]
As a theoretical contribution, the gift wrapping algorithm exemplifies an early non-divide-and-conquer approach in 1970s computational geometry literature, achieving output-sensitive time complexity and influencing subsequent hull algorithms by prioritizing angular searches over sorting. Introduced by Jarvis in 1973 for planar convex hulls, it extended concepts from Chand and Kapur's 1970 work on polytopes, marking a pivotal shift toward practical, geometry-specific paradigms in the field's formative years.
Real-World Implementations
The gift wrapping algorithm, also known as Jarvis march, has been implemented in established computational geometry libraries for practical use in software applications requiring convex hull computation. In the CGAL (Computational Geometry Algorithms Library), an open-source C++ library widely adopted for geometric modeling and processing, the algorithm is provided as a function for computing 2D convex hulls, particularly suitable for datasets where the number of hull points (h) is small relative to the total points (n), achieving O(nh) time complexity.[20] This implementation supports subsequence extraction for lower and upper hulls and is utilized in domains such as computer-aided design (CAD), medical imaging, and geographic information systems (GIS) where efficient hull computation aids in boundary detection and spatial analysis.[21]
In oceanographic data processing, the algorithm is applied for quality control of in situ measurements from Argo profiling floats, which monitor global ocean temperature and salinity. Researchers employ Jarvis march to construct α-convex hulls—n-sided polygons enveloping temperature-salinity (T/S) profiles derived from the World Ocean Atlas climatology—enabling automated anomaly detection without interpolation errors.[22] For instance, the method classifies entire T/S profiles as valid (inside the hull) or erroneous (outside) using ray-casting point-in-polygon tests, identifying issues like sensor drift or biofouling in floats across ocean basins; validation on sample floats demonstrated high accuracy in identifying anomalies such as sensor drifts.[23] This approach enhances efficiency for handling large Argo datasets, reducing reliance on manual quality checks in real-time ocean monitoring.[24]