# [Purdue-pm] How to sort one dimension of a 2d array

Rick Westerman westerman at purdue.edu
Fri Jan 29 07:18:27 PST 2010

```On Jan 29, 2010, at 9:15 AM, Phillip San Miguel wrote:

> This is probably pretty straight forward, but:
>
> I have a hash of 2d arrays. I want to sort by numerical value
> across one of these dimensions. What would be the syntax for that?
>
> \$table{\$colors}[0..num_of_traces-1][0..num_data_points-1]
>
> I want sort the values in the first (traces) dimension.
>
> When I try to write the sort syntax my head starts spinning.
>
> --
>

I found myself floundering as well but then realized that it was
because I was unsure what you wanted.   Also because the problem is
difficult!

Using an example and using %t instead of %table, let us say you have:

\$t{red}[0,0]
\$t{green}[2,0]
\$t{blue}[1,0]
\$t{blue}[4,0]
\$t{red}[2,0]
\$t{blue}[0,0]

Do you want the sort to look like:

\$t{red}[0,0]
\$t{blue}[0,0]
\$t{blue}[1,0]
\$t{green}[2,0]
\$t{red}[2,0]
\$t{blue}[4,0]

Or like:

\$t{red}[0,0]
\$t{red}[2,0]
\$t{green}[2,0]
\$t{blue}[1,0]
\$t{blue}[0,0]
\$t{blue}[4,0]

In others all color data jumbled together or per-color data sorted?

Assuming the latter (which makes more sense to me) then I would do
multiple sorts so that  the sort would look like:

my %sorted;

@{\$sorted{\$color}} =
sort  { \$a->[0]  <=> \$b->[0] } @{\$table{\$color}}
foreach my \$color (keys %table);

There might be a way to combine the sort into one mega-sort but that
would hurt my brain.   Test program (with more data) is enclosed.
Let us know if you want the data sorted in a different way.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: t.pl
Type: text/x-perl-script
Size: 474 bytes
Desc: not available
URL: <http://mail.pm.org/pipermail/purdue-pm/attachments/20100129/a8014b09/attachment.bin>
-------------- next part --------------

-- Rick
```