in reply to Custom sort with string of numbers
The "Schwartzian Transform" is far less important that it used to be due to#!/usr/bin/perl -w use strict; my @a = ("1-1-2", "6-1-2", "3-1-4", "1-1-1"); @a = sort{ my ($A_chapter,$A_sub_chapter,$A_verse) = split(/[-]/,$a); my ($B_chapter,$B_sub_chapter,$B_verse) = split(/[-]/,$b); $A_chapter <=> $B_chapter or $A_sub_chapter <=> $B_sub_chapter or $A_verse <=> $B_verse }@a; print "@a"; __END__ prints: 1-1-1 1-1-2 3-1-4 6-1-2
updated with better variable names in the sort. Names and code formatting do matter.
Yet another comment: The idea behind the "Schwartzian Transform" is to calculate all this stuff like in the split's in one single pass thru the data and then use the resulting values for comparison in the sort. That idea being that we've saved all this calculation on a per pair comparison basis. The idea of the "Guttman-Rosler Transform" is to make a single string value that can be compared with a string comparison (cmp). I don't think that the OP needs either one.
If you have a choice in formatting data like the OP's case, one way is to choose to add leading zeroes so that the normal cmp sort order "works out", this is the "Guttman-Rosler Transform" without any transformation! ie. @array = sort @array; works.
If the set to be sorted is relatively small, the only thing that really matters is how clear the sort is. I think the above is very clear about what it does.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Custom sort with string of numbers
by Anonymous Monk on Aug 29, 2010 at 06:46 UTC | |
by Marshall (Canon) on Aug 29, 2010 at 07:28 UTC | |
by JavaFan (Canon) on Aug 29, 2010 at 14:46 UTC | |
by Marshall (Canon) on Aug 30, 2010 at 21:09 UTC | |
Re^2: Custom sort with string of numbers
by linuxfan (Beadle) on Aug 29, 2010 at 15:17 UTC |