# parameterized sorting function

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
Hi.

I would like to do radix sort on an array @A of strings having equal
length.  Is there some way to do something like the following?

my @A = @_;
my \$d = length(\$A[0]);
for (my \$pos = \$d - 1; \$pos >= 0; \$pos--) {
@A = sort  sortFunction(\$pos) @A;
displayArray(\$pos, @A);
}
}

sub sortFunction {\$a[\$pos] <=> \$b[\$pos]}

IOW, I would like sortFunction to depend on a parameter.

Thanks.

--
Art Werschulz (agw STRUDEL comcast.net)
207 Stoughton Ave Cranford NJ 07016
(908) 272-1146

## Re: parameterized sorting function

Quoth agw@dsm.fordham.edu:

Use a closure:

my @A = @_;
my \$d = length(\$A[0]);
for my \$pos (reverse 0 .. \$d - 1) {
@A = sort { \$a[\$pos] <=> \$b[\$pos] } @A;
displayArray(\$pos, @A);
}
}

Ben

## Re: parameterized sorting function

BM> Quoth agw@dsm.fordham.edu:
>>
>> I would like to do radix sort on an array @A of strings having equal
>> length.  Is there some way to do something like the following?
>>
>> my @A = @_;
>> my \$d = length(\$A[0]);
>> for (my \$pos = \$d - 1; \$pos >= 0; \$pos--) {
>> @A = sort  sortFunction(\$pos) @A;
>> displayArray(\$pos, @A);
>> }
>> }
>>
>> sub sortFunction {\$a[\$pos] <=> \$b[\$pos]}
>>
>> IOW, I would like sortFunction to depend on a parameter.

BM> Use a closure:

BM>         my @A = @_;
BM>         my \$d = length(\$A[0]);
BM>         for my \$pos (reverse 0 .. \$d - 1) {
BM>             @A = sort { \$a[\$pos] <=> \$b[\$pos] } @A;
BM>             displayArray(\$pos, @A);
BM>         }
BM>     }

or a sort block:

@A = sort { sortFunction(\$pos) } @A;

try looking at Sort::Maker as well. you can create sort functions and
dump the code for copy/paste use or call them directly. it will also
generate very fast sorts.

uri

--
Uri Guttman  ------  uri@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Architecture, Development, Training, Support, Code Review  ------
-----------  Search or Offer Perl Jobs  ----- http://jobs.perl.org ---------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------