Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Closest Pair of Points Problem
In this problem, a set of n points are given on the 2D plane. In this problem, we have to find the pair of points, whose distance is minimum.
To solve this problem, we have to divide points into two halves, after that smallest distance between two points is calculated in a recursive way. Using distances from the middle line, the points are separated into some strips. We will find the smallest distance from the strip array. At first two lists are created with data points, one list will hold points which are sorted on x values, another will hold data points, sorted on y values.
The time complexity of this algorithm will be O(n log n).
Input and Output
Input: A set of different points are given. (2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4) Output: Find the minimum distance from each pair of given points. Here the minimum distance is: 1.41421 unit
Algorithm
findMinDist(pointsList, n)
Input: Given point list and number of points in the list.
Output − Finds minimum distance from two points.
Begin min := ∞ for all items i in the pointsList, do for j := i+1 to n-1, do if distance between pointList[i] and pointList[j]stripClose(strips, size, dist)
Input − Different points in the strip, number of points, distance from the midline.
Output − Closest distance from two points in a strip.
Begin for all items i in the strip, do for j := i+1 to size-1 and (y difference of ithand jth points)findClosest(xSorted, ySorted, n)
Input − Points sorted on x values, and points sorted on y values, number of points.
Output − Find minimum distance from the total set of points.
Begin if nExample
#include#include #include using namespace std; struct point { int x, y; }; intcmpX(point p1, point p2) { //to sort according to x value return (p1.x Output
The minimum distance is 1.41421
