Пример #1
0
 public static void main(String[] args) {
   Point[] points = new Point[500];
   for (int i = 0; i < points.length; i++) {
     points[i] = new Point((int) (Math.random() * 1000000), (int) (Math.random() * 1000000));
   }
   Pair pair = Pair.getClosestPair(points);
   System.out.println(pair.getP1());
   System.out.println(pair.getP2());
   System.out.println(pair.getDistance());
 }
Пример #2
0
  public static Pair distance(
      Point[] pointsOrderedOnX, int low, int high, Point[] pointsOrderedOnY) {
    if (low >= high) {
      return null;
    } else if (low + 1 == high) {
      return new Pair(pointsOrderedOnX[low], pointsOrderedOnX[high]);
    }

    int halfSize = (low + high) / 2;
    Pair p1 = distance(pointsOrderedOnX, low, halfSize, pointsOrderedOnY);
    Pair p2 = distance(pointsOrderedOnX, halfSize + 1, high, pointsOrderedOnY);

    double distance = 0;
    Pair p = null;

    if (p1 == null && p2 == null) {
      distance = Double.MAX_VALUE;
    } else if (p1 == null) {
      distance = p2.getDistance();
      p = p2;
    } else if (p2 == null) {
      distance = p1.getDistance();
      p = p1;
    } else {
      distance = Math.min(p1.getDistance(), p2.getDistance());
      p = ((p1.getDistance() <= p2.getDistance()) ? p1 : p2);
    }

    ArrayList<Point> stripL = new ArrayList<Point>();
    ArrayList<Point> stripR = new ArrayList<Point>();
    for (int i = 0; i < pointsOrderedOnY.length; i++) {
      if ((pointsOrderedOnY[i].getX() <= pointsOrderedOnX[halfSize].getX())
          && (pointsOrderedOnY[i].getX() >= pointsOrderedOnX[halfSize].getX() - distance)) {
        stripL.add(pointsOrderedOnY[i]);
      } else {
        stripR.add(pointsOrderedOnY[i]);
      }
    }

    double d3 = distance;
    int r = 0;
    for (int i = 0; i < stripL.size(); i++) {
      while (r < stripR.size() && stripL.get(i).getY() > stripR.get(r).getY() + distance) {
        r++;
      }

      int r1 = r;
      while (r1 < stripR.size() && stripR.get(r1).getY() <= stripL.get(i).getY() + distance) {
        if (d3 > distance(stripL.get(i), stripR.get(r1))) {
          d3 = distance(stripL.get(i), stripR.get(r1));
          p.p1 = stripL.get(i);
          p.p2 = stripR.get(r1);
        }
        r1++;
      }
    }

    return p;
  }