Fix bugs in grouping and sorting functions with distances