Fact-checked by Grok 2 weeks ago

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. 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. 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. This output-sensitive approach constructs the as an ordered list of vertices in counterclockwise order, making it particularly intuitive for visualizing the boundary formation akin to gift wrapping or stretching around the points. The algorithm's is O(nh), where n is the total number of input points and h is the number of vertices on the , 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 (h = 3). Although less efficient than more optimal algorithms like the (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 tool in , with applications in , , and geographic information systems.

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. This structure forms a convex polygon whose vertices are a subset of the points in S, providing the tightest convex boundary around the set. The gift wrapping algorithm, also known as Jarvis's march, is an output-sensitive method for computing the of a set of n points in the plane by iteratively constructing the boundary polygon. Introduced in 1973, it simulates the process of wrapping a taut or gift paper around the points, starting from an and progressively identifying hull vertices to enclose the entire set. Its output sensitivity means the computational effort scales with both the input size and the number of hull vertices, making it efficient when the is simple. The core purpose of the algorithm is to determine the vertices of the , enabling applications in geometric detection, such as collision avoidance in or shape approximation in , where identifying the enclosing simplifies further analysis of point distributions. Intuitively, it begins at an initial hull point, like the leftmost point, and for each subsequent step, selects the next as the point that forms the smallest counterclockwise with the current , thereby "wrapping" the around the points without enclosing interior ones. This angular selection ensures the resulting is convex and minimal.

Historical Background

The gift wrapping algorithm was first proposed by Ray A. Jarvis in 1973 as a method for identifying the of a of points in the plane. In his seminal paper, "On the Identification of the of a 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 enclosing a set of points. This development occurred amid the emerging field of in the , a period marked by growing interest in efficient geometric algorithms for and . 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. 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 with . 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 computation.

Planar Algorithm

Step-by-Step Description

The gift wrapping algorithm, also known as Jarvis's march, computes the of a of points in the 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 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. 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. 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 . 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.

Pseudocode Implementation

The pseudocode below implements the gift wrapping algorithm (Jarvis March) for computing the of a set of points in the . 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 test using the . 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). 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 = 0 are not selected as "more counterclockwise").
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.

Performance Analysis

Time and Space Complexity

The , also known as , 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 . 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 (or equivalent orientation) relative to all n points to identify the one that forms the smallest angle, ensuring the boundary is traced counterclockwise. 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 , such as in , 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). 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.

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. 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. 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. 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. 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. 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 process inputs up to 10-100 times faster on uniform distributions. For large-scale applications, its O(nh) bound renders it inefficient compared to adaptive algorithms like or Chan's, though it remains valuable for conceptual clarity in curricula.

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. The in d is O(n f_d), where n is the number of points and f_d is the number of (d-1)-facets on the ; 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) 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 , 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. As a simple example, consider constructing the of four points forming a in : 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 volume (or minimizing the 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 .

Variants and Improvements

One notable variant integrates the as a subroutine within Chan's optimal output-sensitive algorithm, which achieves O(n log h) in the by partitioning the point set into subsets, computing initial hulls using an O(n log n) method like on each, and then employing gift wrapping to merge hulls from small subsets of size roughly h, avoiding full scans in each step. Parallel versions of the distribute the search for the next hull across multiple processors, particularly by parallelizing the angular sweep or queries in each wrapping step; for instance, a bulk-synchronous parallel () implementation on the enables efficient computation for large n by synchronizing angle evaluations, yielding near-linear on p processors for balanced workloads. 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 and points without altering the core O(nh) bound.

Applications

Computational Geometry Uses

The gift wrapping algorithm serves as a foundational tool in 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 queries, by using the computed as a coarse filter to eliminate distant candidates and focus on boundary-adjacent points. In preprocessing, the algorithm's incremental edge-finding mechanism aids in constructing Delaunay triangulations, the of , through specialized gift-wrapping steps that extend the planar computation to tetrahedralization in higher dimensions. Beyond direct queries, the gift wrapping algorithm integrates with other geometric primitives, including of lines and curves, where hulls of vertex sets define the boundaries of cells in the arrangement, aiding in topological analysis and zone computations. In , it contributes to defining free space by computing hulls of configurations or their Minkowski sums, which bound collision-free regions and simplify path optimization in robotic . The algorithm's educational value lies in its intuitive, step-by-step process, which mirrors physical gift wrapping and provides a simple implementation for output-sensitive algorithms in courses, emphasizing how performance depends on the hull size rather than solely input scale. As a theoretical contribution, the gift wrapping exemplifies an early non-divide-and-conquer approach in 1970s literature, achieving output-sensitive and influencing subsequent hull algorithms by prioritizing angular searches over sorting. Introduced by in 1973 for planar convex hulls, it extended concepts from 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 libraries for practical use in software applications requiring computation. In the (Computational Geometry Algorithms Library), an open-source C++ library widely adopted for geometric modeling and processing, the algorithm is provided as a for computing s, particularly suitable for datasets where the number of hull points (h) is small relative to the total points (n), achieving O(nh) . This implementation supports subsequence extraction for lower and upper hulls and is utilized in domains such as (CAD), , and geographic information systems (GIS) where efficient hull computation aids in boundary detection and . 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 . 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 without interpolation errors. 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 in floats across ocean basins; validation on sample floats demonstrated high accuracy in identifying anomalies such as sensor drifts. This approach enhances efficiency for handling large Argo datasets, reducing reliance on manual quality checks in real-time ocean monitoring.

References

  1. [1]
  2. [2]
    [PDF] 1 Convex Hulls - Jeff Erickson
    This algorithm is usually called Jarvis's march, but it is also referred to as the gift-wrapping algorithm. Jarvis's march starts by computing the leftmost ...Missing: paper | Show results with:paper<|control11|><|separator|>
  3. [3]
    [PDF] CS 3137 Class Notes 1 Finding the Convex Hull of a 2-D Set of Points
    • Another definition is that the convex hull of a point set S is the intersection of all half-spaces that contain S. In 2-D, half spaces are half-planes, or ...
  4. [4]
    On the identification of the convex hull of a finite set of points in the ...
    An efficient algorithm for determining the convex hull of a finite planar set. Information Processing Letters, 1 (1972), pp. 132-133.
  5. [5]
  6. [6]
    [PDF] 6.1 Geometric Primitives - cs.Princeton
    Jan 26, 2010 · Rotate sweep line around current point in ccw direction. • First point hit is on the hull. • Repeat. 20. Package wrap (Jarvis march).
  7. [7]
    [PDF] Lecture 14 1 Overview 2 Convex Hull 3 Convex Hull Algorithm ...
    Oct 16, 2014 · 4.2 Pseudocode. The pseudocode of Jarvis's March algorithm is shown below: 1. Jarvis(x[1...n], y[1...n]):. 2 l=1. 3 for i from 2 to n: 4 if x[i] ...
  8. [8]
    [PDF] Convex Hull Algorithms - UNIUD
    Jarvis' march (2D) / gift wrapping (3D) simple to code running time: O ... R.A. Jarvis (1973). On the identification of the convex hull of a finite set ...
  9. [9]
    Computing the convex hull of a set of points - bitbanging
    Nov 25, 2020 · The complexity of this algorithm is O ( n h ) where n is the number of the points in the set and h is the number of points on the convex hull.<|control11|><|separator|>
  10. [10]
    [PDF] Convex Hull (chapter 1)
    ▷ Gift wrapping is faster than the O(n log n) algorithms when most of the points are in the interior of the hull. ▷ An algorithm whose running time depends on ...
  11. [11]
    Optimal output-sensitive convex hull algorithms in two and three ...
    Nov 30, 1995 · Optimal output-sensitive convex hull algorithms in two and three dimensions. Published: April 1996. Volume 16, pages 361–368, (1996); Cite this ...
  12. [12]
    [PDF] Convex Hulls: Comparing Theoretical and Practical Runtimes
    Dec 10, 2021 · In this paper, we have implemented and compared the practical and theoretical runtimes of four convex hull algorithms: Gift Wrapping/Jarvis ...
  13. [13]
    Robust gift wrapping for the three-dimensional convex hull
    A conventional gift-wrapping algorithm for constructing the three-dimensional convex hull is revised into a numerically robust one.
  14. [14]
    [PDF] Lecture 26: Convex Hull - CS 4102: Algorithms
    Dec 3, 2019 · Jarvis' Algorithm (Gift Wrapping Method). 55. Idea: Start with extremal point and “wrap” points in counter-clockwise fashion. u. Page 56. Jarvis ...Missing: steps | Show results with:steps
  15. [15]
    An efficient improvement of gift wrapping algorithm for computing the ...
    Mar 21, 2020 · In this paper, we present an efficient improvement of gift wrapping algorithm for determining the convex hull of a finite set of points in R ...Missing: improvements | Show results with:improvements
  16. [16]
    [PDF] Computational Geometry Algorithms and Applications
    Computational geometry emerged from algorithms design and analysis, and is used in computer graphics, GIS, robotics, and other application domains.
  17. [17]
    [PDF] 27 VORONOI DIAGRAMS AND DELAUNAY TRIANGULATIONS
    In any dimension, the gift-wrapping algorithm is a specialization of the convex-hull gift-wrapping algorithm (Chapter 26) to Delaunay triangula- tions ...
  18. [18]
    [PDF] 26 CONVEX HULL COMPUTATIONS - CSUN
    In analogy to a 3D physical realization this operation is therefore known as a “gift-wrapping step,” and these algorithms are known as gift- wrapping algorithms ...
  19. [19]
    Convex Hull Functions - CGAL manual
    This function uses the Jarvis march (gift-wrapping) algorithm [8]. This algorithm requires O(n h) time in the worst case for n input points with h extreme ...
  20. [20]
    2D Convex Hulls and Extreme Points: Hull Subsequence Functions
    CGAL::lower_hull_points_2() · CGAL::upper_hull_points_2(). Implementation. The function uses the Jarvis march (gift-wrapping) algorithm [8]. This algorithm ...
  21. [21]
    An improved method for quality control of in situ data from Argo ...
    Apr 5, 2021 · Jarvis March (1973) algorithm which is also popularly called as gift wrapping algorithm was employed for building these α convex hulls ...<|control11|><|separator|>
  22. [22]
  23. [23]