// C# program to find minimum distance between points
using System;
using System.Linq;
using static System.Math;
using System.Collections.Generic;
class GfG {
// Function to compute Euclidean distance between two points
static double distance(double[] p1, double[] p2){
double dx = p1[0] - p2[0];
double dy = p1[1] - p2[1];
return Sqrt(dx * dx + dy * dy);
}
// Function to find the minimum distance in the strip
static double stripClosest(double[][] strip, double d){
double minDist = d;
// Sort points in the strip by their y-coordinate
Array.Sort(strip, (p1, p2) => p1[1].CompareTo(p2[1]));
for (int i = 0; i < strip.Length; ++i){
// The inner loop runs for at most 7 points
for (int j = i + 1; j < strip.Length &&
(strip[j][1] - strip[i][1]) < minDist; ++j){
minDist = Min(minDist, distance(strip[i], strip[j]));
}
}
return minDist;
}
// Divide and conquer function to find the minimum distance
static double minDistUtil(double[][] points, int left, int right){
// Base case there are 2 or fewer points
if (right - left <= 2){
if (right - left <= 0) return double.MaxValue;
return distance(points[left], points[right - 1]);
}
// Find the midpoint index
int midIndex = left + (right - left) / 2;
double midX = points[midIndex][0];
// Recursively find the minimum distances
// in the left and right halves
double dl = minDistUtil(points, left, midIndex);
double dr = minDistUtil(points, midIndex, right);
double d = Min(dl, dr);
// Build the strip of points whose x-coordinate
// is within distance 'd' from the mid
List<double[]> stripList = new List<double[]>();
for (int i = left; i < right; ++i){
if (Abs(points[i][0] - midX) < d){
stripList.Add(points[i]);
}
}
double[][] stripArray = stripList.ToArray();
// Find the minimum distance in the strip
double stripDist = stripClosest(stripArray, d);
return Min(d, stripDist);
}
// Function to find the closest pair of points
static double minDistance(double[,] points2D){
int n = points2D.GetLength(0);
double[][] points = new double[n][];
for (int i = 0; i < n; i++){
points[i] = new double[] { points2D[i, 0], points2D[i, 1] };
}
// Sort points by x-coordinate
Array.Sort(points, (p1, p2) => p1[0].CompareTo(p2[0]));
return minDistUtil(points, 0, n);
}
static void Main(){
double[,] points = {
{ -1, -2 },
{ 0, 0 },
{ 1, 2 },
{ 2, 3 },
{ 5, 1 },
{ 6, 3 },
{ 8, 0 },
{ 9, 2 }
};
double res = minDistance(points);
// Output the result with 6 decimal places
Console.WriteLine(res.ToString("F6"));
}
}