in reply to Sorting by Array values, obtaining indices

PetaMem,
Sort the indices but use the values as the test.
my @idx = sort {$val[$a] <=> $val[$b]} 0 .. $#vals
Though I question the argument that hashes take up more space as a legitimate reason not to use them?

Cheers - L~R

Replies are listed 'Best First'.
Re^2: Sorting by Array values, obtaining indices
by PetaMem (Priest) on Jun 27, 2005 at 16:36 UTC
    Though I question the argument that hashes take up more space as a legitimate reason not to use them?

    Do you?

    use strict; use Devel::Size qw(total_size); my %hash = ( 0 => 3, 1 => 7, 2 => 5, 3 => 0, 4 => 2, ); my @vals = qw(3 7 5 0 2); print 'T1: ', total_size(\%hash),"\n"; print 'T2: ', total_size(\@vals),"\n";

    30% less space for the array, same access speed. There need to be as many of these data structures in memory as possible. qed

    Bye
     PetaMem
        All Perl:   MT, NLP, NLU

      And hashes can be more efficient if there are holes in the index.
      use strict; use Devel::Size qw(total_size); my %hash = ( 0 => 3, 1 => 7, 2 => 5, 3 => 0, 20202 => 2, ); my @vals = qw(3 7 5 0); $vals[20202] = 2; print 'T1: ', total_size(\%hash),"\n"; print 'T2: ', total_size(\@vals),"\n"; [waswas:/var/tmp] waswas% perl hah T1: 291 T2: 131228


      -Waswas
      PetaMem,
      Yeah. I know they take up more space and can be slower than arrays WRT accessing. The work involved in making an array work when a hash makes natural sense almost always outweighs the benefit gained by not using the hash.

      Let me put it another way. When you need to access something by key then a hash is almost always the way to go. I feel that with the amount of information originally given, it was not unexpected to question the motives of using an array over a hash. I am not saying there is never a reason not to use a hash - it is just good to get a sanity check first.

      Cheers - L~R