In place sorting using Perl isn't hard at all. And you don't need
funky tricks like modifying $a and $b.

We all remember our fundamental algorithms, don't we?


Abigail

#!/opt/perl/bin/perl

use strict;
use warnings 'all';

sub heapify ($$$$) {
    my ($code, $index, $array, $bound) = @_;
    {
        my $child = 2 * $index;
        my $max = $index;
        foreach my $offset (0 .. 1) {
            my $child = $child + $offset;
            $max = $child if do {local ($a => $b) = @$array [$max => $child];
                                 $child < $bound && &$code < 0};
        }
        return if $max == $index;
        @$array [$index => $max] = @$array [$max => $index];
        $index = $max;
        redo;
    }
}

sub hsort (&@) {
    my $code = shift;
    my $j = my $i = @_;
                                 heapify $code, $j, \@_, @_ while $j --;
    @_ [0 => $i] = @_ [$i => 0], heapify $code,  0, \@_, $i while -- $i;
    
}


# Call it like:  hsort {$a <=> $b} @array;

Reply via email to