I'm not really seeing the issue with an infinite loop. It seems like you are looping through your clusters and finding all the clusters that need to be merged, then in a separate loop doing the merging and are getting tripped up when two clusters are flagged in such a way that they both need to be merged into one another. Instead, you can think of this as more of a queue.
Then you can loop through one time and merge the small clusters with their neighbors and then destroy them.
Imagine you have a
cluster class with attributes:
members, and nearestNeighbor, and methods
Then you could do something like:
for (cluster in clusterList):
This will only cycle through clusterList one time and will instantly merge and destroy the clusters that are smaller than T.
Assuming you have experience with object oriented programming, this would be pretty straightforward to implement. Even if you do this within an array, you can just
pop clusters after you merge them with other clusters.
Hope this helps!