stable sort

P

Praveen Kallakuri

hello,

i am having a problem with stable sort.

************************************************************
use strict;
use sort 'stable';

.....
....

foreach my $key (sort { $a <=> $b && $sums{$b} <=> $sums{$a} } keys
%sums) {
printf TMPFILE "%d\n",$key;
}
print OUT "\n";
....
....
************************************************************
sums is a hash with the following key-value pairs:


2 3
3 4
4 2
5 4
6 3

i want the hash sorted by the values, but the sequence of keys to be
preserved when possible. so, what i am expecting is something like 3 5 2 6
4. but what i get is below:

3
5
6
2
4

why can't i get the 6 after 2 even though i am using stable sort? thanks
for any suggestions. btw i am using perl 5.8 on a debian-woody.

thanks

praveen
 
B

Benjamin Goldberg

[snip]
foreach my $key (sort { $a <=> $b && $sums{$b} <=> $sums{$a} } keys
%sums) {

Why are you using && between these clauses, instead of || ?

Try writing your code as:

foreach my $key (sort {
$a <=> $b or
$sums{$a} <=> $sums{$b}
} keys %sums) {

The "use sort 'stable'" only means that if you have a sort comparator
which considers two keys of your original list as being equal to each
other, they will appear in the same relative order in the output as they
appeared in the input. For example, consider:

my @a = qw(foo bar quux};
my @b = sort {0} @a;

If you've done "use sort 'stable';" then you're guaranteed that @b will
be in the same order as @al; otherwise, the order might be arbitrary or
random.

Here's a slightly more real-life-ish

my @a = qw(3foo 2bar 2baz 1quux);
my @b = sort { no warnings 'numeric'; $a <=> $b } @a;

With "use sort 'stable';" then 2bar will definitely come before 2baz,
since they're numerically equal and 2bar came before 2baz in the
original array. Without it, their relative order might be arbitrary or
random.

For another real-life-ish example of "arbitrary" -- I remember an old
qsort, which, if you gave it data and a the comparator which considered
everything to be all equal, the output would be the reversed order of
the input.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top