Make delicious recipes!

Find two elements with minimum difference in two arrays

Problem: Given two arrays, find two elements (one in each array) such that their difference is minimum

Solution : Sort both the arrays

Then follow an algorithm like this:
// Start at the beginning of both the arrays
int i=0;
int j=0;

// Initialize minDiff to max-value
int minDiff = Integer.MAX_VALUE;

while (i < arr1.length && j < arr2.length)
    int diff = Math.abs(arr1[i] - arr2[j]);
    if (diff < minDiff)
        minDiff = diff;
    // Move the smaller array's index forward
    if (arr1[i] < arr2[j])

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal