Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the two most similar values in an array (Java)

I have an array of integers and I want to find the two most similar values (least difference).

Example: if the values in the array are 80,100,500,600,501,505, The two most similar values are 500 and 501. How can I do this?

like image 381
Asker Avatar asked Jan 15 '23 19:01

Asker


2 Answers

That seems small task, we can solve this problem as:

1: Apply any efficient sorting algorithm.

2:Then compare adjacent element and pick up whose difference is less.

code is here:

void nearestFinder(){
   int array[];
//apply  sorting algorithm - say selection sort
pre_diff = 0;
new_array = selection_sort(array);
   for(int i =0;i<new_array.length();i++){
      diff = Math.abs(new_array[i]-new_array[i+1]);
      if(diff>pre_diff){
       index =i;
       pre_diff =diff;
       }

      }
print(new_array[index],new_array[index+1])
}
like image 91
MrYo Avatar answered Jan 27 '23 23:01

MrYo


The trick to this problem is sorting the array first. This will make it so you only need to compare numbers that are adjacent to each other; selecting the 2 that have the smallest difference.

psuedocode:

sort the array: use Arrays.sort()
 int max_difference = Integer.MAXVALUE
int val1, val2;
for(i=0; i< array_size -1; ++i) {
 int x = array[i+1] - array[i];
 if(x <= max_difference) {
   max_difference = x;
   val1 = array[i];
   val2 = array[i+1];
 }
}

at the end, val1 and val2 will contain the 2 most similiar values.

like image 44
Colin D Avatar answered Jan 27 '23 23:01

Colin D