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?
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])
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With