### Sorting based on a specific order

by byteflow (Initiate)
 on Jan 02, 2011 at 06:19 UTC Need Help??

byteflow has asked for the wisdom of the Perl Monks concerning the following question:

Greetings. In a script I am developing, I need to sort a list of tokens in a specific order that is hardcoded. But the tokens themselves are not alphabetically or numerically sortable.

That didn't make any sense. An example will demonstrate:

The hardcoded order of teacher favorites is:
Jim, Tony, Bob, John, Tom, Tim

Now, if the given list is
Bob, Tim, Tony

I want this list to be sorted by the hardcoded order of favorites, and return:
Tony, Bob, Tim.

Another example input list:
Tom, John, Jim

would have the output:
Jim, John, Tom.

Hope that made sense. Basically, sort the given list based on a hardcoded (predefined) order, when the tokens themselves have no alphanumeric significance.

Any ideas would be greatly appreciated. Thanks!

Replies are listed 'Best First'.
Re: Sorting based on a specific order
by PeterPeiGuo (Hermit) on Jan 02, 2011 at 06:27 UTC

Here is one solution: use a hash to store the predetermined order - teacher's name as the key and the value could be an integer that determines the order.

#### Peter (Guo) Pei

```my @order = ...;
my %order = map { \$order[\$_] => \$_ } 0..\$#order;

my @sorted = sort { \$order{\$a} <=> \$order{\$b} } @unsorted;
Re: Sorting based on a specific order
by JavaFan (Canon) on Jan 02, 2011 at 16:04 UTC
I assume your ordered teachers are in an array @preferred, and your unsorted teachers are in @unsorted Then,
```my %order = do {my \$i = 0; map {\$_ => \$i++} @preferred};
my @sorted;
\$sorted[\$order{\$_}] = \$_ for @unsorted;
@sorted = grep {defined} @sorted;
No sort() needed. Expected runtime: O(N), where N is the total number of teachers.
Re: Sorting based on a specific order
by Not_a_Number (Prior) on Jan 02, 2011 at 17:40 UTC

Or even (no sorting, no array index arithmetic):

```my %wanted = map { \$_ => 1 } @unsorted;
my @sorted = grep { \$wanted{\$_} } @preferred;
Update: corrected typo 'arthimetic'.
Re: Sorting based on a specific order
by byteflow (Initiate) on Jan 02, 2011 at 18:41 UTC
Thanks everyone for your responses! I particularly appreciate a new understanding of the power of map and grep.

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://880052]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-19 03:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found