http://qs1969.pair.com?node_id=182640


in reply to Re: Sorting by geographical proximity / clumping groups of items based on X and Y
in thread Sorting by geographical proximity / clumping groups of items based on X and Y

  return sqrt( abs( $x2 - $x1 )**2 + abs( $y2 - $y1 )**2 ) ; The abs() isn't necessary, since the result of squaring the difference will always be positive.

For purposes of ordering pairs by distance, it is sufficient to sum the squared differences and sort on distance^2, deferring the sqrt() until a true distance is necessary. (I picked up this trick from Jon Bentley's "Writing Efficient Programs," which is out of print, but worth grabbing if you find a copy in a used bookstore.)

You can also exclude from consideration, before sorting, any pair that has a difference in either dimension that is > X. Such pairs will be excluded anyway, so why clog up the sort with them.