UNSORTED VERSION: Write a Java program that uses “brute force” to find the closest pair, given N distinct integer points in 1-dimension. That is, all points are integers on the x-axis, and are in an array. This algorithm should go through all pairs (without sorting the elements of the array), one pair at a time, to find the current closest pair. For example, assume we had the following integers: 4, 2, -2, -1 in an array. We would then generate the following pairs: [4,2] , [4,-2] , [4,-1] , [2,-2] , [2,-1] , [-2,-1]. Your program should be able to enter the points manually, or from a file. Run your program on 1000 integers.
CODE
import java.util.Scanner;
public class Main {
public static void findClosestPair(int arr[]) {
int x1 = 0, x2 = 0;
int min = Integer.MAX_VALUE;
for (int i=0; i<arr.length; i++) {
for (int j=0; j<arr.length; j++) {
if(i == j) {
continue;
}
if (Math.abs(arr[i] - arr[j]) < min) {
min = Math.abs(arr[i] - arr[j]);
x1 = arr[i];
x2 = arr[j];
}
}
}
System.out.println("The closest points are: (" + x1 + ", " + x2 + ")");
}
public static void main(String[] args) {
int arr[] = new int[1000];
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1000 integers: ");
for (int i=0; i<arr.length; i++) {
arr[i] = sc.nextInt();
}
findClosestPair(arr);
}
}
Get Answers For Free
Most questions answered within 1 hours.