Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 28 additions & 41 deletions src/main/java/com/thealgorithms/geometry/ConvexHull.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.thealgorithms.geometry;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
Expand All @@ -26,7 +28,7 @@ private ConvexHull() {
}

private static boolean checkPointOrientation(Point i, Point j, Point k) {
int detK = Point.orientation(i, j, k);
int detK = orientation(i, j, k);
if (detK > 0) {
return true; // pointsLeftOfIJ
} else if (detK < 0) {
Expand Down Expand Up @@ -69,6 +71,7 @@ public static List<Point> convexHullBruteForce(List<Point> points) {
* @return the convex hull points in counter-clockwise order
*/
public static List<Point> convexHullRecursive(List<Point> points) {
points = new ArrayList<>(new LinkedHashSet<>(points));
if (points.size() < 3) {
List<Point> result = new ArrayList<>(points);
Collections.sort(result);
Expand All @@ -87,7 +90,7 @@ public static List<Point> convexHullRecursive(List<Point> points) {
List<Point> lowerHull = new ArrayList<>();

for (int i = 1; i < points.size() - 1; i++) {
int det = Point.orientation(leftMostPoint, rightMostPoint, points.get(i));
int det = orientation(leftMostPoint, rightMostPoint, points.get(i));
if (det > 0) {
upperHull.add(points.get(i));
} else if (det < 0) {
Expand All @@ -105,14 +108,14 @@ public static List<Point> convexHullRecursive(List<Point> points) {
private static void constructHull(Collection<Point> points, Point left, Point right, Set<Point> convexSet) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The initial upper/lower split and the final angle sort and collinearity filter still call Point.orientation(), which computes the cross product entirely in int. Please use the same overflow-safe orientation throughout the recursive hull. The squared-distance tie-breaker in the angle sort also needs to respect the supported coordinate range.

if (!points.isEmpty()) {
Point extremePoint = null;
int extremePointDistance = Integer.MIN_VALUE;
BigInteger extremePointDistance = null;
List<Point> candidatePoints = new ArrayList<>();

for (Point p : points) {
int det = Point.orientation(left, right, p);
if (det > 0) {
BigInteger det = cross(left, right, p);
if (det.signum() > 0) {
candidatePoints.add(p);
if (det > extremePointDistance) {
if (extremePointDistance == null || det.compareTo(extremePointDistance) > 0) {
extremePointDistance = det;
extremePoint = p;
}
Expand Down Expand Up @@ -154,54 +157,38 @@ private static List<Point> sortCounterClockwise(List<Point> hullPoints) {
sorted.remove(finalPivot);

sorted.sort((p1, p2) -> {
int crossProduct = Point.orientation(finalPivot, p1, p2);

if (crossProduct == 0) {
// Collinear points: sort by distance from pivot (closer first for convex hull)
long dist1 = distanceSquared(finalPivot, p1);
long dist2 = distanceSquared(finalPivot, p2);
return Long.compare(dist1, dist2);
}
int crossProduct = orientation(finalPivot, p1, p2);

// Positive cross product means p2 is counter-clockwise from p1
// We want counter-clockwise order, so if p2 is CCW from p1, p1 should come first
return -crossProduct;
});

// Build result with pivot first, filtering out intermediate collinear points
// Hull vertices are strictly convex, so no two of them are collinear with the pivot.
List<Point> result = new ArrayList<>();
result.add(finalPivot);

if (!sorted.isEmpty()) {
// This loop iterates through the points sorted by angle.
// For points that are collinear with the pivot, we only want the one that is farthest away.
// The sort places closer points first.
for (int i = 0; i < sorted.size() - 1; i++) {
// Check the orientation of the pivot, the current point, and the next point.
int orientation = Point.orientation(finalPivot, sorted.get(i), sorted.get(i + 1));

// If the orientation is not 0, it means the next point (i+1) is at a new angle.
// Therefore, the current point (i) must be the farthest point at its angle. We keep it.
if (orientation != 0) {
result.add(sorted.get(i));
}
// If the orientation is 0, the points are collinear. We discard the current point (i)
// because it is closer to the pivot than the next point (i+1).
}
// Always add the very last point from the sorted list. It is either the only point
// at its angle, or it's the farthest among a set of collinear points.
result.add(sorted.getLast());
}
result.addAll(sorted);

return result;
}

/**
* Computes the squared distance between two points to avoid floating point operations.
* Cross product of (b - a) and (c - a), computed exactly. The coordinate differences are
* widened to long before they are multiplied, and the products can still be larger than a
* long, so BigInteger is used.
*/
private static BigInteger cross(Point a, Point b, Point c) {
BigInteger abx = BigInteger.valueOf((long) b.x() - a.x());
BigInteger aby = BigInteger.valueOf((long) b.y() - a.y());
BigInteger acx = BigInteger.valueOf((long) c.x() - a.x());
BigInteger acy = BigInteger.valueOf((long) c.y() - a.y());
return abx.multiply(acy).subtract(aby.multiply(acx));
}

/**
* Sign of the cross product of (b - a) and (c - a): positive when c is left of the line from a to b.
*/
private static long distanceSquared(Point p1, Point p2) {
long dx = (long) p1.x() - p2.x();
long dy = (long) p1.y() - p2.y();
return dx * dx + dy * dy;
private static int orientation(Point a, Point b, Point c) {
return cross(a, b, c).signum();
}
}
43 changes: 43 additions & 0 deletions src/test/java/com/thealgorithms/geometry/ConvexHullTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,47 @@ void testRecursiveHullForCoverage() {
assertEquals(expectedCollinear, resultCollinear, "Should correctly handle collinear points on the hull edge");
assertTrue(isCounterClockwise(resultCollinear), "The result of the collinear test should be in counter-clockwise order");
}
@Test
void testConvexHullRecursiveExcludesInteriorPoints() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a regression with large positive and negative coordinates. I compiled this revision and checked the triangle (-32768, -32768), (32768, -32768), (-32768, 32768). The initial split treats the three points as collinear after the cross product wraps to zero, and the result drops (32768, -32768).

// (1,8) is strictly inside the hull of the other four points.
List<Point> points = new ArrayList<>(List.of(new Point(1, 5), new Point(1, 8), new Point(2, 9), new Point(0, 10), new Point(4, 19)));
List<Point> expected = List.of(new Point(1, 5), new Point(2, 9), new Point(4, 19), new Point(0, 10));
assertEquals(expected, ConvexHull.convexHullRecursive(points));

// (7,2) and (8,3) are strictly inside the triangle (4,0), (11,3), (3,10).
List<Point> points2 = new ArrayList<>(List.of(new Point(4, 0), new Point(7, 2), new Point(8, 3), new Point(11, 3), new Point(3, 10)));
List<Point> expected2 = List.of(new Point(4, 0), new Point(11, 3), new Point(3, 10));
assertEquals(expected2, ConvexHull.convexHullRecursive(points2));
}

@Test
void testConvexHullRecursiveDuplicatePoints() {
List<Point> points = new ArrayList<>(List.of(new Point(5, 5), new Point(5, 5)));
List<Point> expected = List.of(new Point(5, 5));
assertEquals(expected, ConvexHull.convexHullRecursive(points));
}

@Test
void testConvexHullRecursiveLargeCoordinates() {
// Differences between these coordinates overflow int when multiplied.
List<Point> points = new ArrayList<>(List.of(new Point(-32768, -32768), new Point(32768, -32768), new Point(-32768, 32768)));
List<Point> expected = List.of(new Point(-32768, -32768), new Point(32768, -32768), new Point(-32768, 32768));
assertEquals(expected, ConvexHull.convexHullRecursive(points));
}

@Test
void testConvexHullRecursiveFullIntRange() {
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
// Square corners, one point on a corner-to-corner diagonal and one inside.
List<Point> points = new ArrayList<>(List.of(new Point(min, min), new Point(max, min), new Point(max, max), new Point(min, max), new Point(0, 0), new Point(min, 0), new Point(max, 0), new Point(0, max)));
List<Point> expected = List.of(new Point(min, min), new Point(max, min), new Point(max, max), new Point(min, max));
assertEquals(expected, ConvexHull.convexHullRecursive(points));
}

@Test
void testConvexHullBruteForceLargeCoordinates() {
List<Point> points = new ArrayList<>(List.of(new Point(-32768, -32768), new Point(32768, -32768), new Point(-32768, 32768)));
assertEquals(3, ConvexHull.convexHullBruteForce(points).size());
}
}