http://qs1969.pair.com?node_id=399954

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

Brethren,

I have a reference to a 2-D array ($xy) of floats. I would like to sort the y values (in descending order), but ideally I would like the x values to follow the sorting of y. One implementation that I came up with uses a hash as shown below to make a new array of x values that follows the y sort, but I'm sure there's a more efficient way to do this. My 2-D array can be pretty large (10k - 100k data points), so I'm interested in speed. Thanks for your suggestions.

my @x = @{$xy->[0]}; my @y = @{$xy->[1]}; my $i = 0; my %xyhash; foreach ( @x ) { $xyhash{ $_ } = $y[$i]; $i++ } my @x_sorted_by_y = sort{ $xyhash{$b} <=> $xyhash{$a} } keys %xyhash; my @sorted_y = sort{ $b <=> $a } @y; print "value of x with largest y = $x_sorted_by_y[0]\n"; print "largest y = $sorted_y[0] \n";

Regards chinman