MathGroup Archive 2002

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Friendly Challenge 2: sort by column

MathGroup readers and challenge participants,

Now that I have let a few days go by, allowing time for those who
would choose to participate to write and post their methods, I will
share the function that I have been using.

First, for Hartmut Wolf, who wrote:


what do you mean "handling duplicates" exactly? 

Merely the behavior of the program when there are identical items in
the sort column, possibly resulting in ambiguity.  In general I prefer
the Rotate solution as it more closely follows the default behavior of
Sort.  Of course, this is slower however.


And there you have it!  That's all that I was after. :-)

Next, to DrBob, who wrote:

Another interpretation (the one I prefer) is to preserve preexisting
order in case of ties.  That allows us to sort by one column, then by
another, and get the result we'd expect.

After some experimentation, I found that hw4 and hw5 (and hence
itself) preserve order already, without modification.

As you will see, this is included in my function with the following

positionSort[a, n] uses Rotate
positionSort[a, {n}] sorts by only column n, preserving other
positionSort[a, {n, o, ...} sorts secondarily by o, etc.
n can be negative to give the column n from the end.
A third argument can be given to specify an arbitrary sort function.

Here is a variation of the function that I use.  The original code
uses pattern matching differently (in place of the If statement, for
example), and is too verbose for posting, though it yields a small
improvement in performance:

Cell["Array test function", "Text"],

    \(mtest = #~TensorRank~2 > 1 &\)], "Input"],

Cell["Optional sort function handling", "Text"],

    \(zz = 
        z : \(\((_Symbol | _Function | _Sequence)\) : 
            Sequence[]\)]\)], "Input"],

Cell["Handling of trivial parameters", "Text"],

    \(positionSort[a_, 0 | {0}] := a\), "\n", 
    \(positionSort[a_List, 1] := Sort@a\)}], "Input"],

Sort by only one column (disregard the rest); arbitrary sort function\
\>", "Text"],

    \(positionSort[a_?mtest, {p_Integer} | \(p : {_Integer .. }\), 
        zz] := a\[LeftDoubleBracket]
        a\[LeftDoubleBracket]All, p\[RightDoubleBracket]~Ordering~
          z\[RightDoubleBracket]\)], "Input"],

Cell["Arbitrary sort function", "Text"],

    \(positionSort[a_?mtest, p_Integer, zz] := 
      a\[LeftDoubleBracket]a~RotateLeft~{0, If[p < 0, p, p - 1]}~
          Ordering~z\[RightDoubleBracket]\)], "Input"]


  • Prev by Date: RE: Re: Friendly Challenge 2: sort by column
  • Next by Date: RE: Varying color in ParametricPlot
  • Previous by thread: RE: Re: Friendly Challenge 2: sort by column
  • Next by thread: RE: Re: Friendly Challenge 2: sort by column