Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
m (→‎[[Toka]]: Added full example and further comments)
Line 206: Line 206:
'''Interpreter:''' perl 5.8.8
'''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 $len = @_ - 1;
sub bubble_sort (@) {
my $len = @_ - 1;
for my $i (0 .. $len - 1){
for my $i (0 .. $len - 1){
for my $j ($i + 1 .. $len){
for my $j ($i + 1 .. $len){
if ($_[$j] lt $_[$i]) {
if ($_[$j] lt $_[$i]) {
@_[$i, $j] = @_[$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
Alternate "Long Hand" Perl Method


sub Bubble_Sort {
<highlightSyntax language=perl>
my @list = @_;
sub Bubble_Sort {
my @list = @_;
my $temp = 0;
my $temp = 0;
my $done = 0;
my $done = 0;
my $elements = $#list + 1;
my $elements = $#list + 1;
while ($done == 0) {

while ($done == 0) {
$done = 1;
$done = 1;
for (my $i = 0; $i < $elements; $i++) {
for (my $i = 0; $i < $elements; $i++) {
if ($list[$i] > $list[$i + 1] && ($i + 1) < $elements) {
if ($list[$i] > $list[$i + 1] && ($i + 1) < $elements) {
$done = 0;
$done = 0;
$temp = $list[$i];
$temp = $list[$i];
$list[$i] = $list[$i + 1];
$list[$i] = $list[$i + 1];
$list[$i + 1] = $temp;
$list[$i + 1] = $temp;
}
}
}
}
}
}
return @list;
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]]==
==[[Pop11]]==