Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Used <a href="http://en.wikipedia.org/wiki/Heapsort#Pseudocode" rel="nofollow">pseudocode</a></p> <pre><code>use strict; use warnings; my @a = reverse 1..500; heapSort(\@a); print "@a\n"; sub heapSort { my ($a) = @_; # input: an unordered array a of length count # (first place a in max-heap order) heapify($a); my $end = $#$a; # //in languages with zero-based arrays the children are 2*i+1 and 2*i+2 while ($end) { # (swap the root(maximum value) of the heap with the last element of the heap) @$a[$end, 0] = @$a[0, $end]; # swap(a[end], a[0]) # (decrease the size of the heap by one so that the previous max value will # stay in its proper placement) $end--; # (put the heap back in max-heap order) siftDown($a, 0, $end); } } sub heapify { my ($a) = @_; my $count = @$a; # (start is assigned the index in a of the last parent node) my $start = ($count - 2 ) / 2; while ($start &gt;= 0) { #(sift down the node at index start to the proper place such that all nodes below # the start index are in heap order) siftDown($a, $start, $count-1); $start--; #(after sifting down the root all nodes/elements are in heap order) } } sub siftDown { my ($a, $start, $end) = @_; # input: end represents the limit of how far down the heap # to sift. my $root = $start; while ($root * 2 + 1 &lt;= $end) { # (While the root has at least one child) my $child = $root * 2 + 1; # (root*2 + 1 points to the left child) my $swap = $root; # (keeps track of child to swap with) #(check if root is smaller than left child) $swap = $child if $a-&gt;[$swap] &lt; $a-&gt;[$child]; #(check if right child exists, and if it's bigger than what we're currently swapping with) $swap = $child + 1 if $child+1 &lt;= $end and $a-&gt;[$swap] &lt; $a-&gt;[$child+1]; # (check if we need to swap at all) if ($swap != $root) { # swap(a[root], a[swap]) @$a[$root, $swap] = @$a[$swap, $root]; $root = $swap; # (repeat to continue sifting down the child now) } else { return; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload