Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

RE: Sorting an Associative Array?

by awwaiid (Friar)
on Jul 13, 2000 at 03:15 UTC ( #22301=note: print w/replies, xml ) Need Help??

in reply to Sorting an Associative Array?

If its really big go for the Schwartzian Transform. You would end up with something like this:

@sorted = map {$_->[1]} sort { $a[0] <=> $b->[0] } map { [$_[4],$_] } @unsorted;

The second line (the "<==> part") might need to be changed if you are sorting something other than numbers. This technique is excelent for very complicated structures, very big structures, and is just neat overall :)


Replies are listed 'Best First'.
RE: RE: Sorting an Array?
by maverick (Curate) on Jul 13, 2000 at 18:36 UTC
    minor correction, you need a '->' in the $a in the sort:
    @sorted = map {$_->[1]} sort { $a->[0] <=> $b->[0] } map { [$_[4],$_] } @unsorted;
    and correct me if I'm mistaken (please), but isn't the Schwartzian Transform used in cases where it is necessary to modify the sort key? ie. dictonary sorting mixed case words.

      Thanks for the correction :)

      Naw, the transform doesn't have to modify the sort key... its more general purpose than that (though that is an excellent use). It is just a good algorithm for sorting (array based) data that is more complicated (and or a lot larger) than a plain array. Recently, for instance, I had an array of hashes, and used the transform to sort the array by the contents of one of the hash items.

      For instance, if we had a phone book or something, consisting of an array of hashes, each hash being an entry ($phonebook[0]{firstname} would access the firstname, for example) we could do the transform to sort by say... or something.

      @sorted_phonebook = map {$_->[1]} sort {$a->[0] cmp $b->[0]} map {[$_{lastname},$_]} @phonebook;

      Now, we could indeed do a more complex grabbing of the field we are sorting by and/or a more complex sort algorithm, one in which we needed to modify the key even, but the transform is useful for this case as well.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (None)
    As of 2021-10-17 21:50 GMT
    Find Nodes?
      Voting Booth?
      My first memorable Perl project was:

      Results (72 votes). Check out past polls.