0

array of odd length ( 15 ):

a = np.array([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5])
np.argsort(a)

output = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]


array of odd length ( 17 ):

a = np.array([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5])
np.argsort(a)

output = [ 0 14 13 12 11 10 9 15 8 6 5 4 3 2 1 7 16]


array of odd length ( 35 ):

a = np.array([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5])
np.argsort(a)

output = [ 0 19 20 21 22 23 24 18 25 27 28 29 30 31 32 26 33 17 15 1 2 3 4 5 6 16 7 9 10 11 12 13 14 8 34]



array of even length (16):

a = np.array([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5])
    np.argsort(a)

output = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]


array of even length ( 18 ):

a = np.array([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5])
print len(a)

output = [ 0 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 16 17]

array of even length ( 36 ):

a = np.array([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5])
np.argsort(a)

output = [0 20 21 22 23 24 25 19 26 28 29 30 31 32 33 27 18 17 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 34 35]

So would somebody explain me how this algorithm works in case of equal numbers ?

Ahmed Ramzy
  • 839
  • 1
  • 11
  • 18

1 Answers1

4

argsort() uses a configurable sorting algorithm; you can pick between quicksort, mergesort or heapsort. From the argsort documentation:

numpy.argsort(a, axis=-1, kind='quicksort', order=None)

[...]

kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, optional
Sorting algorithm.

The default is quicksort, and as Wikipedia states:

In efficient implementations it is not a stable sort, meaning that the relative order of equal sort items is not preserved.

Numpy's implementation is efficient and it does not preserve the relative order of equal values.

If you need a stable sort, use mergesort instead:

>>> a = np.array([5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5])
>>> np.argsort(a, kind='mergesort')
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34])

Heapsort is not stable either.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343