There's more than one way to do things | |
PerlMonks |
fast, flexible, stable sortby tye (Sage) |
on Aug 27, 2003 at 19:56 UTC ( [id://287149]=CUFP: print w/replies, xml ) | Need Help?? |
I was building sort keys such that a simple strcmp()/memcmp() could be used as the comparison function in a complex sort even before I found Perl (which was just before Perl 4 was released). It turns out that this technique is very handy in Perl because it usually makes for the fastest possible sort by avoiding specifying a comparison function:
The main problem with the technique is that you need to build the key (XFORM) in such a way that the original record can be reconstructed from it (RESTORE). That often makes this technique difficult to use, making it more of a specialized technique, not something you'd feel you could use all the time. I'd previously used techniques that avoid this RESTORE() step but they still weren't general enough or elegant enough to be the one way to sort for me. I finally came up with a technique that I suspect will be "the one way to sort" for me (below). It also has the feature that it produces a "stable" sort, that is, records with identical keys are kept in their original order relative to each other.
If you want to sort parallel lists, then you'd keep the sorted list of indices around:
Back to
Cool Uses for Perl
|
|