Call your function closest_pair(), defined as follows: double closest_pair(doubl
ID: 3922011 • Letter: C
Question
Call your function closest_pair(), defined as follows: double closest_pair(double[] a)
The return value is the distance between the closest pair of values in the array.
This is what I have so far. Not sure where to go from here.
public class Exercise_1_4_16 {
public static double closest_pair(double[] a) {
// Your code here.
double least = Double.MAX_VALUE;
double a1 = a[0];
double a2 = a[1];
for(int i = 0; i<a.length - 1; i++){
double closePair = Math.abs(a[i] - a[i + 1]);
if(closePair < least){
a1 = a[i];
a2 = a[i + 1];
least = closePair;
}
}
double a3 = a2 - a1;
return a3;
}
public static void main(String[] args) {
double[] a = StdIn.readAllDoubles();
StdOut.printf("%6.4f", closest_pair(a));
}
}
Explanation / Answer
// java code
public class Exercise_1_4_16
{
public static double closest_pair(double[] array)
{
// Your code here.
double minimum_distance = Integer.MAX_VALUE;
double [] a = array;
int sizeArray = a.length;
for(int i=0; i< sizeArray; i++)
{
for(int j=i+1; j< sizeArray;j++)
{
minimum_distance = Math.min(minimum_distance, Math.abs( a[i]-a[j]));
}
}
return minimum_distance;
}
public static void main(String[] args)
{
double[] a = {-1,2,23,10,16};
System.out.printf("Closest distance: %6.4f ", closest_pair(a));
}
}
/*
output:
Closest distance: 3.0000
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.