Sorting algorithms/Bubble sort: Difference between revisions

m
m (→‎[[Toka]]: Added full example and further comments)
Line 206:
'''Interpreter:''' perl 5.8.8
 
# Sorts an array in place and returns a copy
<highlightSyntax language=perl>
sub bubble_sort (@) {
# Sorts an array in place and returns a copy
my $elementslen = $#list@_ +- 1;
sub bubble_sort (@) {
for my $leni =(0 @_.. $len - 1;){
for my $ij (0$i + 1 .. $len - 1){
for my $j ($i + 1if ..($_[$j] lt $len_[$i]) {
if ($ @_[$i, $j] lt= $@_[$j, $i]) {;
@_[$i, $j] = @_[$j, $i];}
}
}
} return @_;
}
return @_;
</highlightSyntax>
 
# usage
<highlightSyntax language=perl>
@a = qw/G F C A B E D/;
# usage
bubble_sort(@a);
@a = qw/G F C A B E D/;
bubble_sort(@a);
</highlightSyntax>
 
Alternate "Long Hand" Perl Method
 
sub Bubble_Sort {
<highlightSyntax language=perl>
return my @list = @_;
sub Bubble_Sort {
my @list$temp = @_0;
my $tempdone = 0;
my $doneelements = 0$#list + 1;
my $elements = $#list + 1;
while ($done == 0) {
 
while ( $done == 0) {1;
for (my $donei = 10; $i < $elements; $i++) {
for if (my$list[$i] > $list[$i =+ 0;1] && ($i + 1) < $elements; $i++) {
if ($list[$i] > $list[$i + 1] && ($idone + 1) < $elements)= {0;
$donetemp = 0$list[$i];
$templist[$i] = $list[$i + 1];
$list[$i] = $list[$i + 1] = $temp;
$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>
 
# usage
my @test = (1, 3, 256, 0, 3, 4, -1);
print join(",", Bubble_Sort(@test));
 
==[[Pop11]]==
Anonymous user