• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 400
  • Last Modified:

Nearest neighbour algorithm

Hi,

I'm trying to write a 'nearest neighbour algorithm' which basically finds a certain number of values in an array that are the closest to a certain value. For example, if I have an array of values:

18, 23, 22, 25, 20, 19, 18, 19, 25

I want to get the 6 values that have the least difference between the value 20. So in this case it would be the values:

18, 18, 19, 19, 22, 23

The first thing I did was to get the differences between each value and 20:

public void kneighbour(int[] values) {
         
  int number = values.length;
  float one = -1;
  float middle;
  float[] diff = new float[values.length];
           
  for(int i = 0; i< number; i++) {
     diff[i] = values[number/2] - values[i];
     if(diff[i] < 0) {
     diff[i] = diff[i]*one;
     }
    System.out.println("This difference is : " + diff[i]);
  }

Once I have all the differences how would I go about getting the six least differences??

Guster

0
Guster
Asked:
Guster
  • 2
  • 2
1 Solution
 
klfCommented:
sort the differences in descending order.
0
 
PapaDanielleCommented:
>>Once I have all the differences how would I go about
>> getting the six least differences??

sort the differences in ascending order , ie from least to greatest ...
0
 
GusterAuthor Commented:
how would I be able to relate those differences back to their original array values??
0
 
GusterAuthor Commented:
I think I got it
0
 
PapaDanielleCommented:
OK. Glad to be of help.

Feel free to pass on any other prob.

Cheers

0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now