Java Program to Find the closest pair from two sorted arrays

JavaServer Side ProgrammingProgramming

To find the closest pair from two sorted array, the Java code is as follows −


 Live Demo

public class Demo {
   void closest_pair(int my_arr_1[], int my_arr_2[], int arr_1_len, int arr_2_len, int sum){
      int diff = Integer.MAX_VALUE;
      int result_l = 0, result_r = 0;
      int l = 0, r = arr_2_len-1;
      while (l<arr_1_len && r>=0){
         if (Math.abs(my_arr_1[l] + my_arr_2[r] - sum) < diff){
            result_l = l;
            result_r = r;
            diff = Math.abs(my_arr_1[l] + my_arr_2[r] - result_l);
         if (my_arr_1[l] + my_arr_2[r] > result_l)
      System.out.print("The closest pair that matches two arrays is [" + my_arr_1[result_l] + ", " +
      my_arr_2[result_r] + "]");
   public static void main(String args[]){
      Demo my_ob = new Demo();
      int my_arr_1[] = {56, 78, 99, 11};
      int my_arr_2[] = {33, 12, 69, 87};
      int arr_1_len = my_arr_1.length;
      int arr_2_len = my_arr_2.length;
      int val = 79;
      my_ob.closest_pair(my_arr_1, my_arr_2, arr_1_len, arr_2_len, val);


The closest pair that matches two arrays is [56, 33]

A class named Demo contains a function named ‘closest_pair’, that iterates through both the arrays and checks to see which sum adds up to a number that is very near to a number previously specified. This pair from the array is returned as output. In the main function, a new instance of the Demo class is defined, the arrays are defined, and their lengths are assigned to two variables respectively. The function is called by passing the arrays, their lengths, and the value. The relevant message is displayed on the console.

Published on 08-Jul-2020 12:01:46