I have a 2D array of size n
representing n
number of points in the 3D space, position[][]
for XYZ (e.g. position[0][0]
is X
, position[0][1]
is Y, and position[0][2]
is Z coordinate of point 0.
What I need to do is to do clustering on the points, so to have n/k
number of clusters of size k
so that each cluster consists of the k
closest points in the 3D space. For instance, if n=100
and k=5
, I want to have 20 clusters of 5 points which are the closest neighbors in space.
How can I achieve that? (I need pseudo-code. For snippets preferably in Java)
What I was doing so far was a simple sorting based on each component. But this does NOT give me necessarily the closest neighbors.
- Sort based on X (
position[0][0]
) - Then sort based on Y (
position[0][1]
) - Then sort based on Z (
position[0][2]
)
for (int i=0; i<position.length; i++){
for (int j=i+1; j<position.length; j++){
if(position[i][0] > position[i+1][0]){
swap (position[i+1][0], position[i][0]);
}
}
}
// and do this for position[i][1] (i.e. Y) and then position[i+2][2] (i.e. Z)
I believe my question slightly differs from the Nearest neighbor search with kd-trees because neighbors in each iteration should not overlap with others. I guess we might need to use it as a component, but how, that's the question.