Java Program to Find Out the Minimum Difference between Two Elements Inside an Array

bookmark

import java.util.*;
public class Main
{
    public static void main(String[] args) 
    {
        int[] arr = { 1, 3, 5, 4, 8, 2, 4, 3, 6, 5 };
        int x = 8, y = 3;
        // Calls the minDifference function
        int minimumDiff = minDifference(arr,x,y);
        // Print the minimum difference
        // If the minimum difference is equal to MAX_VALUE then it is invalid
        if(minimumDiff!=Integer.MAX_VALUE)
            System.out.println("The minimum difference is " + minimumDiff);
        else
            System.out.println("Invalid!");
    }
    // User defined function to calculate the minimum difference between two elements
    public static int minDifference(int[] arr, int x, int y)
    {
        int x_iter = arr.length, y_iter = arr.length, min_diff = Integer.MAX_VALUE;
        // traverse throgh the array
        for (int i = 0; i < arr.length; i++)
        {
            // if the current element is `x`
            if (arr[i] == x)
            {
                // set `x_iter` to the current index
                x_iter = i;
                if (y_iter != arr.length)
                {
                    min_diff = Integer.min(min_diff, Math.abs(x_iter - y_iter));
                }
            }
            // if the current element is y
            if (arr[i] == y)
            {
                // set `y_iter` to the current index
                y_iter = i;
                if (x_iter != arr.length)
                {
                    min_diff = Integer.min(min_diff, Math.abs(x_iter - y_iter));
                }
            }
        }
        return min_diff;
    }
}

 


Output:

The minimum difference is 3