Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Sorting a referrenced array and need to sort by specific fields.

by lachoy (Parson)
on Jul 15, 2002 at 02:32 UTC ( [id://181683]=note: print w/replies, xml ) Need Help??


in reply to Sorting a referrenced array and need to sort by specific fields.

You need a custom sort procedure. The following should work:

sub custom_sort { my @a_parts = split /,/, $a; my @b_parts = split /,/, $b; return $a_parts[0] cmp $b_parts[0] || $a_parts[1] cmp $b_parts[1] || $a_parts[2] cmp $b_parts[2]; } # To invoke: my @sorted = sort custom_sort @{ $outputRef };

This would be easier if \@outputRef used arrayrefs for members rather than strings. But like you said, you have no control over that.

Chris
M-x auto-bs-mode

Replies are listed 'Best First'.
Re: Sorting a referrenced array and need to sort by specific fields.
by Abigail-II (Bishop) on Jul 15, 2002 at 09:17 UTC
    You don't need a sort procedure - a block will do fine.

    But in the given sort procedure, you are performing two splits on each comparison. That's quite costly. It's much better to use either a Schwartzian transform, or a Guttman-Rosler-Transform. The former is the simpler, the latter the faster of the two.

    Here's the ST:

    @sorted = map {$_ -> [0]} sort {$a -> [1] cmp $b -> [1] || $a -> [2] cmp $b -> [2] || $a -> [3] cmp $b -> [3]} map {[$_ => split /,/]} @$outputRef;
    And here's the GRT:
    my ($max_symbol, $max_side, $max_account) = (0, 0, 0); foreach (@$outputRef) { my ($symbol, $size, $account) = split /,/; $max_symbol = length $symbol if length $symbol > $max_symbo +l; $max_size = length $size if length $size > $max_size + ; $max_account = length $account if length $account > $max_accou +nt; } my $total = $max_symbol + $max_size + $max_account; @sorted = map {substr $_, $total} sort map {my ($symbol, $size, $account) = split /,/; $symbol .= "\0" x $max_symbol; $size .= "\0" x $max_size; $account .= "\0" x $max_account; substr ($symbol, 0, $max_symbol) . substr ($size, 0, $max_size) . substr ($account, 0, $max_account) . $_} @$outputRe +f;
    The reason why the GRT is faster than ST is because the GRT doesn't have a custom sort routine, where ST does. GRT does more pre-processing work than ST, but that's only linear in the amount of elements to sort, while there will be O (N * log N) comparisons made.

    Abigail

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://181683]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (None)
    As of 2024-04-25 01:41 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found