Ordering

The Ordering usage message is shown below.

? Ordering

Ordering[list] gives the position at which each element of   list appears in Sort[list]. O ... s of the   last n elements of Sort[list]. Ordering[list, n, p] uses Sort[list, p]. More…

The next cell gives us the ordering of a list.

lst = {-2, 4, -5, Sin[2], 4, π, -∞, 4, ∞} ;  ord = Ordering[lst]

{3, 1, 2, 5, 8, 6, 7, 9, 4}


The next cell shows how we can take the results of Ordering and get a sorted
list.  When Ordering is given one or two arguments we get the ordering of a
cononical sort which may not be the ordering of a numerically sorted list.

Part[lst, ord]  Sort[lst]

{-5, -2, 4, 4, 4, π, -∞, ∞, Sin[2]}

{-5, -2, 4, 4, 4, π, -∞, ∞, Sin[2]}


Ordering[lst,4]  gives the first four elements of Ordering[lst].  The second
argument of Ordering can be (All) or an Integer meeting the condition
(-Length[list] ≤ n ≤ Length[list]).  A few cells after
this example we use All as a a second argument for Ordering.

Ordering[lst, 4]

{3, 1, 2, 5}

The next cell gives the last four elements of Ordering[lst].

Ordering[lst, -4]

{6, 7, 9, 4}

The next cell gives the 2^nd through the 4^th elements of  Ordering[lst].

Ordering[lst, {2, 4}]

{1, 2, 5}

The output of the next cell returns with the 3^rd element of Ordering[lst], and ends with the 2^nd from the last element of Ordering[lst].

Ordering[lst, {3, -2}]

{2, 5, 8, 6, 7, 9}


The next cell returns every other element of Ordering[lst] starting with the
first element of (lst) and ending with the last element of (lst).

Ordering[lst, {1, -1, 2}]

{3, 2, 8, 7, 4}


As mentioned above Ordering normally gives the ordering of a cononical sort.  
We can give Ordering a third argument to get the Ordering of another type of
sort.  In the next cell we get the ordering of a numeric sort.

ord2 = Ordering[lst, All, Less]

{7, 3, 1, 4, 6, 8, 5, 2, 9}


The next cell shows how we can take the results of the last Ordering and get
a numerically sorted list.

Part[lst, ord2]  Sort[lst, Less]

{-∞, -5, -2, Sin[2], π, 4, 4, 4, ∞}

{-∞, -5, -2, Sin[2], π, 4, 4, 4, ∞}


In all the examples above Ordering was given a list, but Ordering can work
with expressions having any head as shown in the next cell.

Clear[h] ;  Ordering[h[-2, 4, -5, Sin[2], 4, π, -∞, 4, ∞]]

{3, 1, 2, 5, 8, 6, 7, 9, 4}


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page