I am so new to maple and I dont know what to do exactly! I have 10 numbers, for finding k nearest number to any of this number I need to keep distances between all numbers and sort them, based on these distances I can get which x is the nearest x to current number so:
for i from 1 to 10 do
for j from 1 to 10 do
dist[j] := abs(x[i]-x[j]);
result[i,j] := abs(x[i]-x[j]);
end do;
end do;
for h from 1 to 10 do
for k from 1 to 10 do
arr[k] := result[h,k];
end do;
distances := (quicksort(arr,1,10));
for t from 1 to 10 do
sortedMatrix[h,t] := distances[t];
end do;
end do;
print(sortedMatrix);
Now I have distances and a number, but i dont know what the other number is?
If I understand correctly, you start with an array of N elements and you want, for each of those N elements, the nearest neighbour in that array. My approach would be to just sort the array first and then loop over it, setting each elements nearest neighbour equal to its neighbour in the sorted array.
Example: suppose you have the array [5,1,86,54,23,46]. If you sort that, you get [1,5,23,46,54,86]. To find the nearest neighbours, you go over the array and look at both elements adjacent. For example, 46 has 23 and 54 as neighbouring elements in the sorted array. 45 is closest to 54 so that's his neighbour.
There is no need to calculate all distances (n*n differences) between elements, you only need the distances between neighbouring nodess in the sorted array (2*n differences).
You can expand that for k nearest neighbours by looking to the k nearest neighbours in the sorted array (2*k*n differences).