More loops



I need to use two loops and an if statement to sort the contents of
this array so
that the number go from lowest to highest.

#!/usr/bin/perl

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

## include your code here ##

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

Looking further into this it was revealed to me that I should use a
bubble loop. Such as this:

for (i=0; i<n-1; i++) {
for (j=0; j<n-1-i; j++)
if (a[j+1] < a[j]) { /* compare the two neighbors */
tmp = a[j]; /* swap a[j] and a[j+1] */
a[j] = a[j+1];
a[j+1] = tmp;
}
}

So I tried to implement this:

#!/usr/bin/perl

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

for (i=0; i<n-1; i++) {
for (j=0; j<n-1-i; j++)
if ($array[j+1] < $array[j]) { /* compare the two neighbors */
tmp = $array[j]; /* swap $array[j] and $array[j+1] */
$array[j] = $array[j+1];
$array[j+1] = tmp;
}
}

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

I know I'm close (right?). What am I missing here?

Thanks

Amichai

Relevant Pages

  • multidimensional array in to a MySQL table
    ... Trying to load an multidimensional array into a MySQL table with columns as ... A 'foreach' inside a 'foreach' echo of the array gives the following, ... I've tried allsorts of while and for loops but can't seem to work out how to ... the get the array to work through the first key to fill the row, ...
    (comp.lang.php)
  • Re: [PHP] Foreach question
    ... foreach to loops the contents of the array and echo to print the table and ... Am I able to add a counter within foreach to print the row ... number in each row using echo ?. ... foreach ($array as $val) ...
    (php.general)
  • Re: Global array operations: a performance hit?
    ... as if many DO loops were executed instead than just one. ... global array operations then? ... Note that the usual terminology is something more like "whole array ... once in a while they might also get you faster execution, ...
    (comp.lang.fortran)
  • Re: Puppy Mastiff wants to Nip at Faces
    ... first couple of weeks of an introductory data structures ... it seems to me by my recollection that loops were... ... in my first college textbook on structured programming. ... they did was loop through an array to show how you could easily access ...
    (rec.pets.dogs.behavior)
  • Re: Inefficient code?
    ... line is written to the output file. ... or read it into an array. ... # Backup File Field Positions ... Define 'my %found;' above the loops. ...
    (perl.beginners)