Keep It Simple, Stupid PerlMonks

### Re: Sort routine runs into infinite loop

by pme (Prior)
 on Jan 02, 2016 at 17:35 UTC ( #1151702=note: print w/replies, xml ) Need Help??

in reply to Sort routine runs into infinite loop

Hi punitpawar,

I suppose you want to implement bubble sort (http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#Perl).

This is a working version of your code.

```#!/usr/bin/perl
use strict;

my @array=(12,6,2,9,15);

my (\$i,\$j,\$tmp);

for (\$i=0; \$i<@array; \$i++){

for (\$j=\$i+1;\$j<@array;\$j++){

if (\$array[\$j]<\$array[\$i]){ # '>' reverses the order

\$tmp = \$array[\$j];
\$array[\$j] = \$array[\$i];
\$array[\$i] = \$tmp;

}
}
}

print "array : @array \n";

Replies are listed 'Best First'.
Re^2: Sort routine runs into infinite loop
by GrandFather (Sage) on Jan 02, 2016 at 21:34 UTC

use strict; helps a whole lot less if you:

```my (\$i,\$j,\$tmp);

and actually we are using Perl so you can:

```#!/usr/bin/perl
use strict;
use warnings;

my @array = (12, 6, 2, 9, 15);

for my \$i (0 .. \$#array) {
for my \$j (\$i + 1 .. \$#array) {
@array[\$j, \$i] = @array[\$i, \$j] if \$array[\$j] < \$array[\$i];
}
}

print "array : @array \n";

If you'd used warnings you'd have caught the error in the process of fixing the warnings.

Premature optimization is the root of all job security
Re^2: Sort routine runs into infinite loop
by hotchiwawa (Scribe) on Jan 02, 2016 at 17:50 UTC
So much code...

```my @array=(12,6,2,9,15);
foreach (sort { \$a <=> \$b } @array)
{ print \$_, " "; }

Most assuredly, your code does not implement bubble sort.

```perl -E 'say"2 6 9 12 15"'

So much code...
```\$ perl -e 'print "\$_ " for sort {\$a <=> \$b} qw {2 6 9 12 15}'
2 6 9 12 15
yep, always shorter and finishing with a string :pp

Create A New User
Node Status?
node history
Node Type: note [id://1151702]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2020-10-29 03:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favourite web site is:

Results (267 votes). Check out past polls.

Notices?