Monotone Chain Convex Hull.java

http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull.java
/* This is an implementation of Monotone Chain Convex Hull algorithm in Java.
* It takes O( NlogN ) in sorting & O(N) in actual convex hull finding for N points.
* Author - Nikhil Garg
* Email - nikhilgarg28@gmail.com
* This code is not heavily commented. To understand it, refer to pseudocode.
*/


class Point implements Comparable<Point>
{
int x,y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}

// sort first on x then on y
public int compareTo(Point other)
{
if( x == other.x)
return y - other.y;
else
return x - other.x;
}

// cross product of two vectors
public int cross( Point p)
{
return x * p.y - y * p.x;
}

// subtraction of two points
public Point sub( Point p)
{
return new Point( x - p.x, y - p.y );
}

}


public Point[] findHull( Point[] points)
{
int n = points.length;
Arrays.sort( points);
Point[] ans = new Point[2 * n]; // In between we may have a 2n points
int k = 0;
int start = 0; // start is the first insertion point



for(int i = 0; i < n; i ++) // Finding lower layer of hull
{
Point p = points[i];
while( k - start >= 2 && p.sub( ans[k-1] ).cross(p.sub( ans[k-2] ) ) > 0 )
k--;
ans[k++] = p;
}

k--; // drop off last point from lower layer
start = k ;

for(int i = n-1 ; i >= 0 ; i --) // Finding top layer from hull
{
Point p = points[i];
while( k - start >= 2 && p.sub( ans[k-1] ).cross(p.sub( ans[k-2] ) ) > 0 )
k--;
ans[k++] = p;
}
k--; // drop off last point from top layer

Point [] ret = new Point[k]; // ret would contain our convex hull to be returned.
for(int i = 0 ; i < k; i++)
ret[i] = ans[i];
return ret;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值