Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
(→[[Perl]]: syntax highlight) |
|||
Line 185: | Line 185: | ||
'''Interpreter:''' perl 5.8.8 |
'''Interpreter:''' perl 5.8.8 |
||
<highlightSyntax language=perl> |
|||
# Sorts an array in place and returns a copy |
|||
sub bubble_sort (@) { |
|||
⚫ | |||
my $len = @_ - 1; |
|||
for my $i (0 .. $len - 1){ |
|||
for my $j ($i + 1 .. $len){ |
|||
if ($_[$j] lt $_[$i]) { |
|||
@_[$i, $j] = @_[$j, $i]; |
|||
⚫ | |||
} |
|||
} |
} |
||
⚫ | |||
return @_; |
|||
# Usage |
|||
} |
|||
⚫ | |||
</highlightSyntax> |
|||
⚫ | |||
<highlightSyntax language=perl> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
</highlightSyntax> |
|||
Alternate "Long Hand" Perl Method |
Alternate "Long Hand" Perl Method |
||
<highlightSyntax language=perl> |
|||
sub Bubble_Sort { |
|||
my @list = @_; |
|||
my @list = @_; |
|||
my $temp = 0; |
|||
my $done = 0; |
|||
⚫ | |||
while ($done == 0) { |
|||
while ($done == 0) { |
|||
$done = 1; |
|||
for (my $i = 0; $i < $elements; $i++) { |
|||
$ |
if ($list[$i] > $list[$i + 1] && ($i + 1) < $elements) { |
||
$ |
$done = 0; |
||
$ |
$temp = $list[$i]; |
||
$list[$i |
$list[$i] = $list[$i + 1]; |
||
$list[$i + 1] = $temp; |
|||
} |
} |
||
} |
|||
} |
|||
return @list; |
|||
} |
|||
</highlightSyntax> |
|||
<highlightSyntax language=perl> |
|||
⚫ | |||
# usage |
|||
my @test = (1, 3, 256, 0, 3, 4, -1); |
|||
print join(",", Bubble_Sort(@test)); |
|||
</highlightSyntax> |
|||
==[[Python]]== |
==[[Python]]== |