Program CPAlgorithm(Input, Output);

TYPE 
  Cell =  RECORD
            p: POINT;
            next: ^Cell;
          END;
  Link = ^Cell;

CONST MaxDistance = 1.0E30;

VAR
   min   : REAL;
   h,z    : Link;
   N: INTEGER;

@CheckforMin
PROCEDURE CheckforMin (p1, p2: Point) =@
  VAR dist: REAL;
  BEGIN
@5     IF (dist(p1,p2) < min) THEN @
@10       updatemin(p1,p2); @
  END;
@CheckforMin


@FindClosestPair
PROCEDURE FindClosestPair(VAR c: Link; N: INTEGER): Link =@
  VAR
    a, b, t1, t2  : Link;
    middle_xcoord : REAL;
    p1, p2, p3, p4: Point;

  BEGIN
@5    a := c;@
@10   b := MiddleofList(c,N);@
@15   middle_xcoord := b^.p.x;@

@20   t1 := FindClosestPair(a, N DIV 2);@
@25   t2 := FindClosestPair(b, N - (N DIV 2));@

@30   c := Merge(t1, t2);@

@35   a := c;@
      REPEAT
@40     IF ((ABS(a^.p.x - middle_xcoord) < min) AND (p1 <> z^.p)) THEN@
        BEGIN
@45       CheckforMin(a^.p, p1);@
@50       CheckforMin(a^.p, p2);@
@55       CheckforMin(a^.p, p3);@
@60       CheckforMin(a^.p, p4);@
@65       p1 := p2; p2 := p3; p3 := p4; p4 := a^.p;@
        END { IF };
@70     a := a^.next;@
@75   UNTIL a = z;@

@80 RETURN c;@
  END;
@FindClosestPair


@Main
BEGIN {main module: computes closest pair in given set of points} @

@5   InitializeListofPoints(h,N);@

@10  h := Sort_byXcoordinate(h, N);@

@15  h := FindClosestPair(h, N);@

END.
@Main
