# java – Finding the distance between two smallest array elements

## Question:

The task is: "Create a console application that would take a series of numbers as input and output the distance between the two smallest ones. For example, given a series of numbers:" 23 45 34 12 45 4 38 56 2 49 100 ". The smallest numbers in it are 2 and 4. The distance between them is 3 (meaning the difference between the modulo indices)"

``````public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
System.out.println("Enter random numbers:");
int size = scan.nextInt();
int[] mas = new int[size];

for (int i = 0; i < size; i++) {
mas[i] = scan.nextInt();
}

int indexOfMax = mas;
int indexOfMin = mas;
for (int i = 0; i < mas.length; i++) {
if(mas[i] > indexOfMax)
indexOfMax = mas[i];

if(mas[i] <indexOfMin)
indexOfMin = mas[i];
}
System.out.println(indexOfMax+" "+indexOfMin);
}
``````

that is, I fill the array with values ​​​​from the console. I decided to try to find at least the minimum and maximum values ​​.. did not work. The maximum is found every time, and the minimum is always 0.

how to find the 2 minimum values ​​of an array entered from the console? (not sorting the array)

``````public static void main(String[] args) {
int[] mas = {23, 45, 34, 12, 45, 4, 38, 56, 2, 49, 100};

int min1 = Integer.MAX_VALUE;
int min2 = Integer.MAX_VALUE;
int index1 = 0;
int index2 = 0;
for (int i = 0; i < mas.length; i++) {
if( mas[i] < min1) {
min2 = min1;
min1 = mas[i];
index2 = index1;
index1 = i;
} else if (mas[i] < min2) {
min2 = mas[i];
index2 = i;
}
}
System.out.println(Math.abs(index1 - index2));
}
``````
Scroll to Top