Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: RFC: I rewrote a custom sort function, but not sure if it is the best way.

by 7stud (Deacon)
on Mar 03, 2013 at 02:15 UTC ( #1021482=note: print w/replies, xml ) Need Help??

in reply to RFC: I rewrote a custom sort function, but not sure if it is the best way.

Let's start with the premise that a sort routine shouldn't be longer than 10 lines. What can you do to comply with that restriction?

It looks to me like you are doing a lot of array processing inside the sort routine. Why not process the whole array first, then apply your sort routine? The advantage of processing your array before sorting is that you only touch each element once, where sort touches the elements multiple times.

The next question is: why do you think you need one sort routine to sort every conceivable array you might conjure up? A better way would be to do something like this:

use strict; use warnings; use 5.010; my %sort_by = ( article => \&article_sorter, name => \&name_sorter, subject => \&subject_sorter, ); my @results = $sort_by{name} @data

Once again, by doing that you are moving some of the processing out of the sort routine by checking for the type before calling sort().

Next comes advanced sorting, i.e. efficient sorting. As davido mentioned, it is a great learning process to learn how to do a Schwartzian Transform or use an Orcish Manouvre in your sort routine. Okay, even though they sound like theorems you might learn about in a Theoretcial Physics class, they are quite easy to grok.

But if you fail to fully grasp the above means for efficient sorting, not to worry--there is a module that will help you out called Sort::Maker.

  • Comment on Re: RFC: I rewrote a custom sort function, but not sure if it is the best way.
  • Download Code

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1021482]
[marioroy]: Is List::Util::XS a core Perl module?
[stevieb]: corelist List::Util::XS says "List::Util::XS was first released with perl v5.10.1"
[stevieb]: so yes, since v5.10.1 :)
[MidLifeXis]: According to [metaperl:// corelist], Perl 5.10.1
Lady_Aleena blurbles. One of her favorite modiles is now in "maintenance mode" in favor of a new fangled module.
[MidLifeXis]: D'oh. Slow out of the gate.
[marioroy]: Thanks stevieb, MidLifeXis.

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (12)
As of 2017-05-24 17:52 GMT
Find Nodes?
    Voting Booth?