Sorting algorithms/Bubble sort: Difference between revisions

Content added Content deleted
(Undo revision 124529 by 38.116.192.95 (talk) Vandalism)
Line 2,028: Line 2,028:
</lang>
</lang>


01 #!/usr/bin/perl
=={{header|Perl}}==
02
<lang perl># Sorts an array in place
sub bubble_sort {
03 sub bubblesort {
for my $i (0 .. $#_){
04 my $array = shift;
05
for my $j ($i + 1 .. $#_){
$_[$j] < $_[$i] and @_[$i, $j] = @_[$j, $i];
06 my $i; # The initial index for the bubbling scan.
07 my $j; # The running index for the bubbling scan.
}
08 my $ncomp = 0; # The number of comparisons.
}
09 my $nswap = 0; # The number of swaps.
}</lang>
10

11 for ( $i = $#$array; $i; $i-- ) {
Usage:
12 for ( $j = 1; $j <= $i; $j++ ) {

<lang perl>my @a = (39, 25, 30, 28, 36, 72, 98, 25, 43, 38);
13 $ncomp++;
14 # Swap if needed.
bubble_sort(@a);</lang>
15 if ( $array->[ $j - 1 ] gt $array->[ $j ] ) {
16 @$array[ $j, $j - 1 ] = @$array[ $j - 1, $j ];
17 $nswap++;
18 }
19 }
20 }
21 print "bubblesort: ", scalar @$array,
22 " elements, $ncomp comparisons, $nswap swaps\n";
23 }
24
25 @array = qw(question auteurity and eat the rich goodness of duncan hines);
26
27 bubblesort \@array;
28
29 print "@array\n";


=={{header|Perl 6}}==
=={{header|Perl 6}}==