Add a grouping function that both sorts and uses a distance function to determine grouping