0

I am using the sort_index() function in c++ armadillo, and it does not seem to give the correct result:

input vector is [3,4,2,1,5] sorting both directions

arma::sort_index(input, "ascend").print();
arma::sort_index(input, "descend").print();

and obtain the following results: [3,2,0,1,4] and [4,1,0,2,3]

which neither is correct. Sorting according to ascending order should give [2,3,1,0,4] (doubled checked with numpy.searchsorted and it gives the above result).

--- Edit ---

Thanks for the replies! I realize now that I misunderstood the way sort_index is indexing. I am still trying to find an efficient, equivalent function that achieves np.searchsorted in c++...

segfault_101
  • 51
  • 1
  • 3
  • 1
    How do you arrive at your expected result? The smallest item is at index `3` (value `1`), the second smallest item is at index `2` (value `2`), the third smallest item is at index `0` (value `3`) and so on. – walnut Jan 27 '20 at 23:21
  • Do you mean you checked with `numpy.argsort`? Could you post your expected result, and the numpy code that double-checks it? – NicholasM Jan 27 '20 at 23:27
  • It looks like sort_index[0] is giving you the current index of the value that would be sorted to index 0, while you're expecting it to be the sorted index of the value currently at index 0, if that makes sense – Nic Jan 28 '20 at 00:14

1 Answers1

2

Armadillo's documentation states that

sort_index( X )
sort_index( X, sort_direction )
Return a vector which describes the sorted order of the elements of X (ie. it contains the indices of the elements of X)

The returned vector corresponds to the indexes of the elements in the original vector X that would result in a sorted vector.

The corresponding function in numpy is argsort and not searchsorted. Indeed argsort from numpy will give the same solution as sort_index in armadillo.

In your example [3,4,2,1,5] the smallest element is in index 3, folowed by the element in index 2, then 0 and so one. In order words, if you too elements in X using indexes [3,2,0,1,4] you would get the vector [1, 2, 3, 4, 5], which is X sorted.

darcamo
  • 3,294
  • 1
  • 16
  • 27
  • Ah got it! Thanks :) – segfault_101 Jan 28 '20 at 01:56
  • I am trying to find a c++ equivalent of ```searchsorted```, is there an armadillo function that would achieve the same result as ```searchsorted```? – segfault_101 Jan 28 '20 at 01:58
  • @segfault_101 There is no such function in armadillo, but armadillo is not focused into inserting elements into an existing vector. It would also be inefficient to do this, since all elements after the element just inserted would need to be moved. You might want to use a different data structure for that. – darcamo Jan 28 '20 at 16:45