develooper Front page | perl.fwp | Postings from July 2001

Re: Sorting in-place

Thread Previous | Thread Next
From:
merlyn
Date:
July 25, 2001 17:05
Subject:
Re: Sorting in-place
Message ID:
m1wv4wd07k.fsf@halfdome.holdit.com
>>>>> "Clinton" == Clinton A Pierce <clintp@geeksalad.org> writes:

Clinton> 	@dummy=sort {
Clinton> 		$r=$a cmp $b;
Clinton> 		if ($r < 0) {
Clinton> 			($a,$b)=($b,$a);
Clinton> 			$r=1;
Clinton> 		}
Clinton> 		$r;
Clinton> 		} @list;
Clinton> 	# Is @list sorted?  Not quite...

Clinton> Except this doesn't work.  Oh, $a and $b get modified and they're swapped
Clinton> at appropriate times, but the resulting mess in @list can hardly be called
Clinton> proper ordering.

For this to work, the element indirected by $a would have to always be
to the left of the element indirected by $b, and that's probably not
true.  In fact, we can see this:

@dummy = sort {
  print "$a $b\n";
  $a <=> $b;
} 1..9;

4 5
5 6
3 5
2 5
1 5
5 7
5 8
5 9
7 6
8 7
9 8
2 1
3 2
4 3

See the last few?  If you were to swap the 4/3 pair to put them
in order, you're actually taking them *out* of order.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About