Sorting points by their polar angle in Java

前端 未结 3 1464
礼貌的吻别
礼貌的吻别 2021-01-04 20:12

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-04 21:09

    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!

提交回复
热议问题