Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

I need some serious help with this "bubble sort". Has anyone tried to do this before? I keep going into a infinite loop!

#!/usr/bin/perl

@array = (5,3,2,1,4);

while ($array[$_] > $array[$_ + 1]){
print "$array\n";
if ($array == 1) {
if ($array == 2){
print "Before: ", join(' ', );
$_--;
}
}
}

foreach $elem (@array){
print "$elem";
}

Use two loops and an if statement to sort the contents of the array so that the number go from lowest to highest. (This is actually a very inefficient way to sort an array.)

HINT: One loop should progress through the array comparing and swapping adjacent elements (if necessary). The second loop is used to make sure this happens multiple times based on the size of the array.


Why do you use $_ in the

Why do you use $_ in the while statement? $_ is not initialised with any meaningful value at the beginning of your script.

I would use another variable name instead of $_; also, don't forget to initialise it.

I originally had...

$i=0, but wasn't sure if that was correct.