In this program, we are going to **find the minimum distance between two numbers using the Java** programing language. If you are a **Java beginner** and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share **how to write a Java program to find the minimum distance between two numbers**.

Copy the below Java program and execute it with the help of Javac compiler. At the end of this program, We have shared the output of this program.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | class JavaMinimumDistanceProgram { int minDist(int arr[], int n, int x, int y) { int i, j; int min_dist = Integer.MAX_VALUE; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > Math.abs(i - j)) min_dist = Math.abs(i - j); } } return min_dist; } public static void main(String[] args) { MinimumDistance min = new MinimumDistance(); int arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3}; int n = arr.length; int x = 3; int y = 6; System.out.println("Minimum distance between " + x + " and " + y + " is " + min.minDist(arr, n, x, y)); } } |

Minimum distance between 2 and 5 is 2

Liked this program? Do Like & share with your friends.

- Java program to calculate power of a number
- How to remove duplicate characters from String in Java?
- Fibonacci Series in Java Without Recursion
- Iterate value through Java HashMap
- Java program to remove punctuation from a given string
- Java Program to Implement Fisher-Yates Algorithm for Array Shuffling
- Java Program to Implement Gauss Seidel Method
- Java Program to Implement Gauss Jordan Elimination
- A Simple Merge based O(n) solution to find median of two sorted arrays
- Java program to count islands in boolean 2D matrix

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok