Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
Underscore (talk | contribs) (Added Perl 6.) |
Underscore (talk | contribs) (→{{header|Perl}}: Deleted longhand implementation. Shortened the first implementation and fixed a fencepost error. Switched from stringwise to numeric sorting.) |
||
Line 914: | Line 914: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
⚫ | |||
{{works with|Perl|5.8.8}} |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
my $ |
for my $j ($i + 1 .. $#_){ |
||
$_[$j] < $_[$i] and @_[$i, $j] = @_[$j, $i]; |
|||
⚫ | |||
if ($_[$j] lt $_[$i]) { |
|||
@_[$i, $j] = @_[$j, $i]; |
|||
} |
|||
} |
} |
||
} |
} |
||
return @_; |
|||
}</lang> |
}</lang> |
||
<lang perl># usage |
|||
@a = qw/G F C A B E D/; |
|||
⚫ | |||
Usage: |
|||
Alternate "Long Hand" Perl Method |
|||
<lang perl>my @a = (39, 25, 30, 28, 36, 72, 98, 25, 43, 38); |
|||
<lang perl>sub Bubble_Sort { |
|||
⚫ | |||
my @list = @_; |
|||
my $temp = 0; |
|||
my $done = 0; |
|||
my $elements = $#list; |
|||
while ($done == 0) { |
|||
$done = 1; |
|||
$elements--; |
|||
for (my $i = 0; $i < $elements; $i++) { |
|||
if ($list[$i] > $list[$i + 1]) { |
|||
$done = 0; |
|||
$temp = $list[$i]; |
|||
$list[$i] = $list[$i + 1]; |
|||
$list[$i + 1] = $temp; |
|||
} |
|||
} |
|||
} |
|||
return @list; |
|||
}</lang> |
|||
<lang perl># usage |
|||
my @test = (1, 3, 256, 0, 3, 4, -1); |
|||
print join(",", Bubble_Sort(@test));</lang> |
|||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |