下边的代码仅仅是凸包求法的一个简单模拟,并没有经过严格的测试,并且我们假设没有任意两个点在一条直线上,且点的个数大于等于3,
package coursera.week2.sort;
public class Point2D {
private double x;
public void setX(double x){
this.x = x;
}
public double getX() {
return x;
}
private double y;
public void setY(double y){
this.y = y;
}
public double getY() {
return y;
}
public Point2D(double x,double y){
this.x = x;
this.y = y;
}
public static int ccw(Point2D a, Point2D b, Point2D c){
double ans = (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);
if(ans > 0){ //ccw counter-clockwise
return 1;
}
else if(ans < 0){ //clockwise
return -1;
}
else{ //colinear
return 0;
}
}
}
package coursera.week2.sort;
import java.awt.print.Printable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Stack;
import sun.net.www.content.audio.x_aiff;
import com.sun.org.apache.xml.internal.security.Init;
public class Graham {
Stack<Point2D> hull = new Stack<Point2D>();
private Point2D[] p;
private Point2D pYMin;
public Graham(Point2D[] p){
this.p = p;
init();
}
public void init(){
Arrays.sort(p, new Point2D_Y());//now p[0].y is the smallest.
pYMin = p[0]; //save the point with min y
Arrays.sort(p, new Polar()); //sort the p with polar ascending
}
public void scanner(){
hull.push(p[0]);
hull.push(p[1]);
int n = p.length;
for(int i = 2; i<n; i++){
Point2D top = hull.pop();
while(Point2D.ccw(hull.peek(), top, p[i])<=0){
hull.pop();
}
hull.push(top);
hull.push(p[i]);
}
}
class Point2D_Y implements Comparator<Point2D>{
@Override
public int compare(Point2D p, Point2D q) {
//注意,此方法实现从小到大排序
if(p.getY() >= q.getY()) return 1;
return -1;
}
}
class Polar implements Comparator<Point2D> {
@Override
public int compare(Point2D p, Point2D q) {
if(polar(p) >= polar(q)){
return 1;
}
return -1;
}
}
private double polar(Point2D p){
Double x = p.getX()-pYMin.getX();
Double y = p.getY()-pYMin.getY();
if(x==0)
return -10;
return Math.atan2(y,x);
}
public void print(){
while(!hull.empty()){
Point2D p = hull.pop();
System.out.println(p.getX()+""+p.getY());
}
}
}