Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Unusual sorting requirements; comparing three implementations.

by moritz (Cardinal)
on Oct 24, 2012 at 17:11 UTC ( #1000670=note: print w/replies, xml ) Need Help??

in reply to Unusual sorting requirements; comparing three implementations.

You can exploit that fact that sort is stable, and do two passes over the data:

sub two_pass { my @sorted = sort { $b->title =~ /Manager/ <=> $a->title =~ /Manager/ } sort { $a->name cmp $b->name } @employees; }

Moo wouldn't install on my machine, so I used Mo instead for benchmarking:

Rate obvious subtle two_pass functional obvious 173/s -- -22% -30% -61% subtle 222/s 28% -- -11% -50% two_pass 249/s 44% 12% -- -44% functional 444/s 156% 100% 79% --

Of course it does more than necessary (splitting into managers and non-managers first is less work, because the lists to sort are shorter), but the speed still isn't too bad.

Update: and here's a Perl 6 solution:

use v6; class Person { has $.name; has $.title; } sub person($name, $title) {$name, :$title) }; my @employees = person("Eve", "Tech Support"), person("Alice", "Sales Manager"), person("Dave", "Janitor"), person("Fred", "Receptionist"), person("Bob", "Customer Services"), person("Greg", "Finance Manager"), person("Carol", "Marketing Manager"), ; my @sorted = @employees.classify({ .title ~~ /Manager/ ?? 'manager' !! 'staff'} +)\*.value.sort(*.name)); say .perl for @sorted;

Output: => "Alice", title => "Sales Manager") => "Carol", title => "Marketing Manager") => "Greg", title => "Finance Manager") => "Bob", title => "Customer Services") => "Dave", title => "Janitor") => "Eve", title => "Tech Support") => "Fred", title => "Receptionist")

.classify returns a Hash, and .sort on a Hash returns a list of Pair object, sorted by key and then by value. Since 'manager' lt 'staff', this puts all the managers first. Then each of the lists is sorted by name.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1000670]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2017-04-26 19:46 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (488 votes). Check out past polls.