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 |
03 sub bubblesort { |
||
04 my $array = shift; |
|||
05 |
|||
⚫ | |||
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: |
|||
⚫ | |||
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 } |
|||
⚫ | |||
⚫ | |||
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}}== |