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
In reply to Re: bubble sort in perl
by RMGir
in thread bubble sort in perl
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |