More loops
- From: amichai@xxxxxxxxxx (Amichai Teumim)
- Date: Thu, 28 Jun 2007 12:53:49 +0300
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
- Follow-Ups:
- Re: More loops
- From: Jenda Krynicky
- Re: More loops
- Prev by Date: Re: shuffling cards
- Next by Date: parsing a line
- Previous by thread: shuffling cards
- Next by thread: Re: More loops
- Index(es):
Relevant Pages
|
|