Given an array of integers, find the closest pair, that is, two elements with th
ID: 3658475 • Letter: G
Question
Given an array of integers, find the closest pair, that is, two elements with the smallest distance between their values. For example, in the following array { 3, 4, 9, 7, 5, 1}, the closest pair is either {3, 4} or {4, 5}, since the distance between the two elements in the pair is 1. Please complete the following method. It takes an array as a parameter, and returns a new array of size 2 holding the closest pair. If there are multiple closest pairs, you may return any one of them. public static int[] closestPair(int[] arr) { int[] pair = new int[2]; Arrays.sort(arr); // working on a sorted array should be easier //TO BE FILLED return pair; }Explanation / Answer
import java.lang.Math.*; public class ArrayTester{ //algorithm for finding the distance between the two closest elements in an array of numbers public int MinDistance(int [] ar){ int [] a = ar; int aSize = a.length; int dMin = 0;//MaxInt for(int i=0; iRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.