Distance calculation and distance based sort