Nearest neighbour algorithm


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??


Who is Participating?
>>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 ...
sort the differences in descending order.
GusterAuthor Commented:
how would I be able to relate those differences back to their original array values??
GusterAuthor Commented:
I think I got it
OK. Glad to be of help.

Feel free to pass on any other prob.


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.