I'm trying to implement the Graham’s Scan algorithm for a convex hull in Java, and have trouble sorting the points by polar angle with respect to the point with lowest y-value.
I have found this answer and understand how to calculate the polar angle but not how to sort the points.
I have seen implementations were Collections.sort() is being used but none of them seem to work with the Point2D class which I want to use because I want to be able to have doubles as coordinates.
Basically I want to be able to sort an ArrayList<Point2D> by their polar angle to the point with the lowest y-value in the same ArrayList.
Could someone please help me with this? Thanks.
Let's assume that
initialis thePoint2Dwhich has the lowest Y coordinate. Also, let's assume thatList<Point2D> pointsis a list with all the other points available, but it does NOT contain theinitialpoint.In order to sort the list, we can use
Collections.sortwith the comparator:Edit:
This solution might encounter a division by zero. One way to overcome this is to use a cross product. See this answer from Erfan Alimohammadi.