I\'m using Graham scan algorithm to find the convex-hull of set of points I\'m trying to sort the points by their polar angle but I have no idea how to do it (I\'ve already
As mentioned above, calculating the polar angle itself is a pretty sloppy way of going about things. You can define a simple comparator and use cross products to sort by polar angle. Here is code in C++ (which I use for my own Graham scan):
struct Point {
int x, y;
}
int operator^(Point p1, Point p2) {
return p1.x * p2.y - p1.y * p2.x;
}
bool operator<(Point p1, Point p2)
{
if(p1.y == 0 && p1.x > 0)
return true; //angle of p1 is 0, thus p2 > p1
if(p2.y == 0 && p2.x > 0)
return false; //angle of p2 is 0 , thus p1 > p2
if(p1.y > 0 && p2.y < 0)
return true; //p1 is between 0 and 180, p2 between 180 and 360
if(p1.y <0 && p2.y > 0)
return false;
return (p1 ^ p2) > 0; //return true if p1 is clockwise from p2
}
You can implement the same thing in Java, by defining a Point
class. Basically I have overloaded the ^
operator to return the cross product. The rest is evident, hope this helps!