I think this works:

```python
sort_idx = argsort(distances)
sorted_distances = distances[sort_idx]
sorted_grouping = grouping[sort_idx]
```