Implementation of clustering algorithm