in reply to bubble sort in perl
This isn't even an EFFICIENT bubble sort (hehe), since "isSorted" could be done as part of the bubbling loop, by bubbling until no swaps occur. But this version is probably easier to read.
sub bubble { my $arrRef=shift; foreach my $i(1..@$arrRef-1) { @$arrRef[$i,$i-1]=@$arrRef[$i-1,$i] unless $arrRef->[$i-1]<=$arrRef->[$i]; } } sub isSorted { my $arrRef=shift; my $isSorted=0; foreach my $i(1..@$arrRef-1) { return 0 unless $arrRef->[$i-1]<=$arrRef->[$i]; } return 1; } open(IN,"<raw_data") or die "Can't open raw_data, error $!"; my @raw_data=map {chomp;$_} <IN>; print "Before sort: ",(join ",",@raw_data), "\n"; bubble(\@raw_data) while !isSorted(\@raw_data); print "After sort: ",(join ",",@raw_data), "\n";
If this IS for homework, try to understand it before handing it in, k? Otherwise, your teacher's gonna ask you some tough questions, and you're going to be in deep trouble...
Besides, if your teacher likes perl enough to teach it, he
probably hangs out here with us anyhow :)
--
Mike
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: bubble sort in perl
by particle (Vicar) on Mar 24, 2002 at 13:39 UTC | |
by RMGir (Prior) on Mar 24, 2002 at 13:43 UTC | |
by particle (Vicar) on Mar 24, 2002 at 14:29 UTC | |
by RMGir (Prior) on Mar 24, 2002 at 14:37 UTC | |
|
Re: Re: bubble sort in perl
by Juerd (Abbot) on Mar 24, 2002 at 22:31 UTC |