# [Numpy-discussion] Robust Sorting of Points

Pierre Haessig pierre.haessig at crans.org
Tue Oct 29 06:37:24 EDT 2013

```Hi Freddie,

Le 29/10/2013 10:21, Freddie Witherden a écrit :
> The order itself does not need to satisfy any specific properties.
I can't agree with you : if there is no specific property, then keeping
the list *unchanged* would be a fine solution (and very fast and very
very robust) ;-)

what about defining a comparison function (in the sense of the old cmp
keyword of list.sort) such as :

def compare(point, other):
delta = point - other
argmax = np.abs(delta).argmax()
delta_max = delta[argmax]
if delta_max > 0:
return 1
elif delta_max < 0:
return -1
else:
return 0

This function returns a comparison of the coordinates with the  biggest
absolute difference. Of course this doesn't define an *absolute order*
(since it doesn't exist). But I think it defines a *relative order* (if
this notion exists mathematically !!!!) which is indeed robust.

To apply this comparison function, the simple solution I see (for Python
<3) is, using your first example ;

>>> my_array = np.array([[-0.5, 0, 2**0.5],
[0.5, 0, 2**0.5 - 1e-15]])

>>> l = list(my_array)

>>>  l.sort(cmp = compare)

>>> l
[array([-0.5       ,  0.        ,  1.41421356]),
array([ 0.5       ,  0.        ,  1.41421356])]

step is to plug it either in numpy sorting machinery or in the new
Python sorting which uses a "key function" (cf.
http://docs.python.org/3.3/howto/sorting.html#the-old-way-using-the-cmp-parameter).

best,
Pierre

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 900 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20131029/1e077b49/attachment.sig>
```