function agglomerate($labels, $grid) { $clusters = $labels; while (count($clusters) > 1) { $distances = array(array(1, 0, $grid[1][0])); for ($i = 2; $i < count($grid); $i++) { for ($j = 0; $j < $i; $j++) { $distances[] = array($i, $j, $grid[$i][$j]); } } usort($distances, function ($a, $b) { return $b[2] < $a[2]; }); list($j, $i, $d) = $distances[0]; # merge i⇐j $c = new Cluster($d); list($clusters, $grid) = $c->add($clusters, $grid, $i, $j); $clusters[$i] = $c; } return $clusters[min(0, count($clusters) - 1)]; }