Graham Scan
   HOME

TheInfoList



OR:

Graham's scan is a method of finding the
convex hull In geometry, the convex hull or convex envelope or convex closure of a shape is the smallest convex set that contains it. The convex hull may be defined either as the intersection of all convex sets containing a given subset of a Euclidean space ...
of a finite set of points in the plane with
time complexity In computer science, the time complexity is the computational complexity that describes the amount of computer time it takes to run an algorithm. Time complexity is commonly estimated by counting the number of elementary operations performed by ...
O(''n'' log ''n''). It is named after
Ronald Graham Ronald Lewis Graham (October 31, 1935July 6, 2020) was an American mathematician credited by the American Mathematical Society as "one of the principal architects of the rapid development worldwide of discrete mathematics in recent years". He ...
, who published the original algorithm in 1972. The algorithm finds all vertices of the convex hull ordered along its boundary. It uses a
stack Stack may refer to: Places * Stack Island, an island game reserve in Bass Strait, south-eastern Australia, in Tasmania’s Hunter Island Group * Blue Stack Mountains, in Co. Donegal, Ireland People * Stack (surname) (including a list of people ...
to detect and remove concavities in the boundary efficiently.


Algorithm

The first step in this algorithm is to find the point with the lowest y-coordinate. If the lowest y-coordinate exists in more than one point in the set, the point with the lowest x-coordinate out of the candidates should be chosen. Call this point ''P''. This step takes O(''n''), where ''n'' is the number of points in question. Next, the set of points must be sorted in increasing order of the angle they and the point ''P'' make with the x-axis. Any general-purpose
sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a List (computing), list into an Total order, order. The most frequently used orders are numerical order and lexicographical order, and either ascending or descending. ...
is appropriate for this, for example
heapsort In computer science, heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like selection sort, heapsort divides its input into a sorted and an unsorted region, and it iteratively shrinks the ...
(which is O(''n'' log ''n'')). Sorting in order of angle does not require computing the angle. It is possible to use any function of the angle which is monotonic in the interval ,\pi/math> . The cosine is easily computed using the
dot product In mathematics, the dot product or scalar productThe term ''scalar product'' means literally "product with a scalar as a result". It is also used sometimes for other symmetric bilinear forms, for example in a pseudo-Euclidean space. is an algebra ...
, or the slope of the line may be used. If numeric precision is at stake, the comparison function used by the sorting algorithm can use the sign of the
cross product In mathematics, the cross product or vector product (occasionally directed area product, to emphasize its geometric significance) is a binary operation on two vectors in a three-dimensional oriented Euclidean vector space (named here E), and is ...
to determine relative angles. If several points are of the same angle, either break ties by increasing distance (
Manhattan Manhattan (), known regionally as the City, is the most densely populated and geographically smallest of the five boroughs of New York City. The borough is also coextensive with New York County, one of the original counties of the U.S. state ...
or
Chebyshev Pafnuty Lvovich Chebyshev ( rus, Пафну́тий Льво́вич Чебышёв, p=pɐfˈnutʲɪj ˈlʲvovʲɪtɕ tɕɪbɨˈʂof) ( – ) was a Russian mathematician and considered to be the founding father of Russian mathematics. Chebyshe ...
distance may be used instead of Euclidean for easier computation, since the points lie on the same ray), or delete all but the furthest point. The algorithm proceeds by considering each of the points in the sorted array in sequence. For each point, it is first determined whether traveling from the two points immediately preceding this point constitutes making a left turn or a right turn. If a right turn, the second-to-last point is not part of the convex hull, and lies 'inside' it. The same determination is then made for the set of the latest point and the two points that immediately precede the point found to have been inside the hull, and is repeated until a "left turn" set is encountered, at which point the algorithm moves on to the next point in the set of points in the sorted array minus any points that were found to be inside the hull; there is no need to consider these points again. (If at any stage the three points are collinear, one may opt either to discard or to report it, since in some applications it is required to find all points on the boundary of the convex hull.) Again, determining whether three points constitute a "left turn" or a "right turn" does not require computing the actual angle between the two line segments, and can actually be achieved with simple arithmetic only. For three points P_1 = (x_1,y_1), P_2 = (x_2,y_2) and P_3 = (x_3,y_3), compute the ''z''-coordinate of the
cross product In mathematics, the cross product or vector product (occasionally directed area product, to emphasize its geometric significance) is a binary operation on two vectors in a three-dimensional oriented Euclidean vector space (named here E), and is ...
of the two vectors \overrightarrow and \overrightarrow, which is given by the expression (x_2-x_1)(y_3-y_1)-(y_2-y_1)(x_3-x_1). If the result is 0, the points are collinear; if it is positive, the three points constitute a "left turn" or counter-clockwise orientation, otherwise a "right turn" or clockwise orientation (for counter-clockwise numbered points). This process will eventually return to the point at which it started, at which point the algorithm is completed and the stack now contains the points on the convex hull in counterclockwise order.


Time complexity

Sorting the points has time complexity O(''n'' log ''n''). While it may seem that the time complexity of the loop is O(''n''2), because for each point it goes back to check if any of the previous points make a "right turn", it is actually O(''n''), because each point is considered at most twice in some sense. Each point can appear only once as a point (x_2,y_2) in a "left turn" (because the algorithm advances to the next point (x_3,y_3) after that), and as a point (x_2,y_2) in a "right turn" (because the point (x_2,y_2) is removed). The overall time complexity is therefore O(''n'' log ''n''), since the time to sort dominates the time to actually compute the convex hull.


Pseudocode

The pseudocode below uses a function ccw: ccw > 0 if three points make a counter-clockwise turn, clockwise if ccw < 0, and collinear if ccw = 0. (In real applications, if the coordinates are arbitrary real numbers, the function requires exact comparison of floating-point numbers, and one has to beware of numeric singularities for "nearly" collinear points.) Then let the result be stored in the stack. let points be the list of points let stack = empty_stack() find the lowest y-coordinate and leftmost point, called P0 sort points by polar angle with P0, if several points have the same polar angle then only keep the farthest for point in points: # pop the last point from the stack if we turn clockwise to reach this point while count stack > 1 and ccw(next_to_top(stack), top(stack), point) <= 0: pop stack push point to stack end Now the stack contains the convex hull, where the points are oriented counter-clockwise and P0 is the first point. Here, next_to_top() is a function for returning the item one entry below the top of stack, without changing the stack, and similarly, top() for returning the topmost element. This pseudocode is adapted from ''
Introduction to Algorithms ''Introduction to Algorithms'' is a book on computer programming by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The book has been widely used as the textbook for algorithms courses at many universities and is co ...
''.


Notes

The same basic idea works also if the input is sorted on x-coordinate instead of angle, and the hull is computed in two steps producing the upper and the lower parts of the hull respectively. This modification was devised by A. M. Andrew. It has the same basic properties as Graham's scan. Graham's original description involved sorting around an interior point of the
convex hull In geometry, the convex hull or convex envelope or convex closure of a shape is the smallest convex set that contains it. The convex hull may be defined either as the intersection of all convex sets containing a given subset of a Euclidean space ...
, rather than one of its vertices. For the same choice of a pivot point for the sorting algorithm, connecting all of the other points in their sorted order around this point rather than performing the remaining steps of the Graham scan produces a
star-shaped polygon In geometry, a star-shaped polygon is a polygonal region in the plane that is a star domain, that is, a polygon that contains a point from which the entire polygon boundary is visible. Formally, a polygon is star-shaped if there exists a poi ...
, a
polygonalization In computational geometry, a polygonalization of a finite set of points in the Euclidean plane is a simple polygon with the given points as its vertices. A polygonalization may also be called a polygonization, simple polygonalization, Hamiltoni ...
of the input. The stack technique used in Graham's scan is very similar to that for the
all nearest smaller values In computer science, the all nearest smaller values problem is the following task: for each position in a sequence of numbers, search among the previous positions for the last position that contains a smaller value. This problem can be solved effici ...
problem, and parallel algorithms for all nearest smaller values may also be used (like Graham's scan) to compute convex hulls of sorted sequences of points efficiently.


Numerical robustness

Numerical robustness In computer science, robustness is the ability of a computer system to cope with errors during execution1990. IEEE Standard Glossary of Software Engineering Terminology, IEEE Std 610.12-1990 defines robustness as "The degree to which a system o ...
is an issue to deal with in algorithms that use finite-precision
floating-point In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can b ...
computer arithmetic. A 2004 paper analyzed a simple incremental strategy, which can be used, in particular, for an implementation of the Graham scan. The stated goal of the paper was not to specifically analyze the algorithm, but rather to provide a textbook example of what and how may fail due to floating-point computations in
computational geometry Computational geometry is a branch of computer science devoted to the study of algorithms which can be stated in terms of geometry. Some purely geometrical problems arise out of the study of computational geometric algorithms, and such problems ar ...
. (An earlier version was reported in 2004 at ESA'2004) Later D. Jiang and N. F. Stewart elaborated on this and using the
backward error analysis In mathematics, error analysis is the study of kind and quantity of error, or uncertainty, that may be present in the solution to a problem. This issue is particularly prominent in applied areas such as numerical analysis and statistics. Error a ...
made two primary conclusions. The first is that the convex hull is a
well-conditioned In numerical analysis, the condition number of a function measures how much the output value of the function can change for a small change in the input argument. This is used to measure how sensitive a function is to changes or errors in the input ...
problem, and therefore one may expect algorithms which produce an answer within a reasonable error margin. Second, they demonstrate that a modification of Graham scan which they call Graham-Fortune (incorporating ideas of Steven Fortune for numeric stabilityFortune, S. Stable maintenance of point set triangulations in two dimensions. Proceedings of the 30th annual IEEE Symposium on Foundations of Computer Science Vol. 30, 494-499, 1989.) does overcome the problems of finite precision and inexact data "to whatever extent it is possible to do so".


See also

*
Convex hull algorithms Algorithms that construct convex hulls of various objects have a broad range of applications in mathematics and computer science. In computational geometry, numerous algorithms are proposed for computing the convex hull of a finite set of points ...


References


Further reading

* {{DEFAULTSORT:Graham Scan Articles with example pseudocode Convex hull algorithms