0

How to identify the 2 closest numbers in an array

I want to write a program that identifies the 2 closest numbers in an int array and then prints their difference

16th Dec 2016, 3:44 PM
Fanis Spirou
Fanis Spirou - avatar
2 ответов
+ 1
Try this: create 2 for loops like this for (int i = 0; i < array.length; i++){ for (int j = i+1; j < array.length; j++){ //Your code here } } Inside check to see the absolute difference of two array items like this Math.abs(array[i] - array[j]); Find the smallest difference and print it out. This is one way to do it.
16th Dec 2016, 3:52 PM
Uran Kajtazaj
Uran Kajtazaj - avatar
0
thank you that seems to be working well. It Can't handle a lot of numbers fast though .You know any other good method?
16th Dec 2016, 4:26 PM
Fanis Spirou
Fanis Spirou - avatar