# Sorting a list of points based on their euclidean distance

I need to take a list of random points and then sort them from least to greatest based on their Euclidean distance from a certain point. How would I do this?

• Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. – bbgodfrey Feb 21 '15 at 16:33

orig = {1, 1};
pts = RandomReal[{0, 1}, {20, 2}];
ordered = Sort[pts, Norm[#1 - orig] > Norm[#2 - orig] &]
Graphics[{PointSize[#[[1]] .01], Point@#[[2]]} & /@  Transpose[{Range@Length@pts, ordered}]]


• Or SortBy[..., Norm[#-orig]&] – Szabolcs Feb 21 '15 at 16:22
pts = RandomReal[{0, 1}, {20, 2}];
ordered2 = pts[[Ordering[-Norm /@ (# - orig & /@ pts)]]]

ordered2 == ordered (* ordered from belisarius's answer *)
(* True *)


Using Sort with a custom ordering function forces quadratic complexity due to pairwise comparison(1)(2)(3)(4)(5) and should be avoided whenever possible. Use SortBy instead, as Szabolcs comments.

orig = {1, 1};

pts = RandomReal[1, {50000, 2}];

Sort[pts, Norm[#1 - orig] > Norm[#2 - orig] &] // AbsoluteTiming // First

SortBy[pts, Norm[# - orig] &]                  // AbsoluteTiming // First

3.911224

0.011001


It is shorter to write too. :-) Ordering is slightly faster still but not as convenient to use.