Sorting according to a primary and secondary criterion

Joseph Rushton Wakeling joseph.wakeling at webdrake.net
Wed Jul 17 04:43:28 PDT 2013


Hi all :-)

Suppose that I have two different arrays of the same length, arr1 and arr2, and
an array of index values idx = [0 .. arr1.length].

Now, suppose that I want to sort the index values according to the corresponding
values of arr1.  This is easy with schwartzSort:

    idx.schwartzSort!(a => arr1[a]);

But suppose now that I want to sort _primarily_ according to arr1, but
secondarily according to arr2?  That is, that the index i should come before j
if arr1[i] < arr1[j], but also if arr1[i] == arr1[j] && arr2[i] < arr2[j] ... ?

One option might be first to sort with respect to arr2 and then to sort with
respect to arr1 using SwapStrategy.stable, but that seems overkill and also
uncertain.

I guess I could do something like,

    .sort!("arr1[a] < arr1[b] || (arr1[a] == arr1[b] && arr2[a] < arr2[b]"));

... but I'm not sure that would be an optimal strategy.

Is there a standard, accepted approach for this kind of sort with
primary/secondary criterion?

Thanks & best wishes,

    -- Joe


More information about the Digitalmars-d-learn mailing list