Advertisement
Guest User

Heapsort

a guest
Dec 23rd, 2013
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. my $N = 10000000;
  7. my @a;
  8.  
  9. sub pushDown {
  10.     my ($pos, $N) = @_;
  11.     while (2 * $pos + 1 < $N) {
  12.         my $j = 2 * $pos + 1;
  13.         if ($j + 1 < $N && $a[$j + 1] > $a[$j]) {
  14.             ++$j;
  15.         }  
  16.         last if $a[$pos] >= $a[$j];
  17.         @a[$pos, $j] = @a[$j, $pos];
  18.         $pos = $j;
  19.     }  
  20. }
  21.  
  22. @a = 0 .. $N-1;
  23.  
  24. pushDown($_, $N) for reverse 0 .. $N / 2;
  25.  
  26. my $n = $N;
  27. while ($n > 1) {
  28.     @a[0, $n - 1] = @a[$n - 1, 0];
  29.     --$n;
  30.     pushDown(0, $n);
  31. }
  32.  
  33. while (my ($id, $key) = each @a) {
  34.     die unless $id == $key;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement