added function to sort distances