Minimum difference between two sorted arrays
Given two arrays sorted in ascending order, find the absolute minimum difference between any pair of elements |a-b| such that a is from one array and b is from another array.
For example consider the following two arrays.
array1 = [3, 27, 45, 68, 70, 81, 99]
array2 = [9, 16, 25, 35, 70, 84]
The minimum difference is 2 (27-25).
This can be calculated using the following algorithm.
Take two indices i, j which point to the beginning of the two arrays (i.e 0)
Take variable MinDiff and assign it the maximum possible value
If array1[i] and array2[j] are equal return 0
Otherwise update MinDiff if abs( array1[i] - array2[j] ) is the new minimum.
If array1[i] > array2[j] move second index(j) forward otherwise move first index (i) forward.
Repeat the above procedure until we reach the end of any of the two arrays.
Finally process the remaining part of left-over array to update MinDiff.
public class MinDifference {
public static void main(String [] args)
{
int [] array1 = {12, 34, 57, 61, 69, 80};
int [] array2 = {27, 39, 48, 51, 79};
System.out.println(findMinDiff(array1,array2));
}
public static int findMinDiff(int[] array1, int[] array2)
{
// sorting array
Arrays.sort(array1);
Arrays.sort(array2);
int i = 0, j = 0;
int minDiff = Integer.MAX_VALUE;
while ( i < array1.length && j < array2.length )
{
if( array1[i] == array2[j] )
return 0;
int diff = Math.abs( array1[i] - array2[j] );
minDiff = Math.min( diff, minDiff );
if( array1[i] > array2[j] )
j++;
else
i++;
}
if( i < array1.length ) //array1 has some more elements
{
j--; // j has reached the end, move it to last element
while ( i < array1.length )
{
int diff = Math.abs( array1[i] - array2[j] );
minDiff = Math.min( diff, minDiff );
i++;
}
}
else //array2 has some more elements
{
i--;
while ( j < array2.length )
{
int diff = Math.abs( array1[i] - array2[j] );
minDiff = Math.min( diff, minDiff );
j++;
}
}
return minDiff;
}
}