7
$\begingroup$

How can I sort a list and also get a list of indices that sort this list? For example: primary list is a

a={1,4,6,7,0,2};

sorted list is b

b={7,6,4,2,1,0}

and also return list c

c={4,3,2,6,1,5}
$\endgroup$

1 Answer 1

10
$\begingroup$

To get list b, you need Sort[]: Sort[{1, 4, 6, 7, 0, 2}, GreaterEqual].

To get list c, you need Ordering[]: Ordering[{1, 4, 6, 7, 0, 2}, All, GreaterEqual].

$\endgroup$
4
  • $\begingroup$ @Heike: I guess there is such a thing as being in the right place at the right time... :) $\endgroup$ Commented Jun 24, 2012 at 12:00
  • $\begingroup$ @J.M. : Thank you $\endgroup$ Commented Jun 24, 2012 at 12:03
  • 6
    $\begingroup$ Also, if you need both, you might first do Ordering and then b=a[[c]] $\endgroup$
    – Rojo
    Commented Jun 24, 2012 at 14:00
  • $\begingroup$ @Rojo: that's a good point with respect to saving sorting effort. :) $\endgroup$ Commented Jun 24, 2012 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.