Implemented union find for merging clusters.