Re: More loops
- From: Jenda@xxxxxxxxxxx (Jenda Krynicky)
- Date: Thu, 28 Jun 2007 14:40:25 +0200
From: "Amichai Teumim" <amichai@xxxxxxxxxx>
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.
@sorted = sort {$a <=> $b} @unsorted;
You can use the builtin function sort(). All you have to do is to
tell it how do you want the elements compared.
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;
}
}
The first thing you are missing are sigils. All variables in Perl
have to start with a sigil ($, @, %, ...).
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;
}
}
Next thing is that you do not need a third variable to exchange the
values of two variables.
($a, $b) = ($b, $a);
is perfectly legal and more efficient.
So you can write the body of the inner loop like this:
($array[j], $array[j+1]) = ($array[j+1], $array[j]);
You may even use so called "array slices". That is instead of writing
($array[j+1], $array[j])
you can write just
@array[j+1,j]
so the body of the loop will be
@array[j,j+1] = @array[j+1,j];
You may also use the foreach style of loop instead of the C-style
for():
foreach my $i (0 .. $#array) {
foreach my $j (0 .. $#array-1-$i) {
if ($array[$j+1] < $array[$j]) {
@array[j,j+1] = @array[j+1,j];
}
}
}
foreach $elem (@array){
print "$elem\n";
}
This can be simplified to
print join("\n", @array), "\n";
Jenda
===== Jenda@xxxxxxxxxxx === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery
.
- Follow-Ups:
- Re: More loops
- From: Chas Owens
- Re: More loops
- References:
- More loops
- From: Amichai Teumim
- More loops
- Prev by Date: pp utility
- Next by Date: Re: shuffling cards
- Previous by thread: More loops
- Next by thread: Re: More loops
- Index(es):
Relevant Pages
|