login

Perl Bubble Sort

In this tutorial, you will learn how bubble sort is implemented in Perl.

#!/usr/bin/perl

sub bubblesort {
    my $array = shift;

    my $i;         # The initial index for the bubbling scan.
    my $j;         # The running index for the bubbling scan.
    my $ncomp = 0; # The number of comparisons.
    my $nswap = 0; # The number of swaps.

    for ( $i = $#$array; $i; $i-- ) {
        for ( $j = 1; $j <= $i; $j++ ) {
            $ncomp++;
            # Swap if needed.
            if ( $array->[ $j - 1 ] gt $array->[ $j ] ) {
                @$array[ $j, $j - 1 ] = @$array[ $j - 1, $j ];
                $nswap++;
            }
        }
    }
    print "bubblesort:  ", scalar @$array,
          " elements, $ncomp comparisons, $nswap swaps\n";
}

@array = qw(question auteurity and eat the rich goodness of duncan hines);

bubblesort \@array;

print "@array\n";