views:

275

answers:

2

I'm kind of stuck with my heap sort here in php:

<?php
function heapSort($a, $count){
    $a = heapify($a, $count);

    $end = $count - 1;
    while ($end > 0){
        $temp = $a[$end];

        $a[$end] = $a[0] ;

        $a[0]= $temp;
        $end = $end - 1;
        siftDown($a, 0, $end);
    }
    return $a;
}


    function heapify($a,$count){
        $start = ($count - 2) / 2;

        while ($start >= 0){
            $a = siftDown($a, $start, $count-1);
            $start = $start - 1;
        }
        return $a;
    }


    function siftDown($a, $start, $end){
        $root = $start;

        while ($root * 2 + 1 <= $end){// While the root has at least one child
            $child = $root * 2 + 1;      // root*2+1 points to the left child
                                         //If the child has a sibling and the 
                                         //child's value is less than its
                                         //sibling's
            if ($child + 1 <= $end and $a[$child] < $a[$child + 1])
                $child = $child + 1;// then point to the right child instead)
            if ($a[$root] < $a[$child]){ // out of max-heap order
                  list($a[$child],$a[$root]) = array($a[$root],$a[$child]);
                $root = $child;      // repeat to continue sifting down
                                     // the child now
            }
            else {
                return $a;
    }}
    return $a;
    }


    $a = Array(3,1,5,2);
    $b = heapSort($a,count($a));
    print_r($b);
    ?>

I can't get to sort the array, any idea what's wrong?

A: 

I'm no PHP expert, but it doesn't seem like heapify is done right -- how can heapification boil down to a bunch of calls to siftDown...? The latter is written assuming it IS dealing with an array that IS a heap (with possibly one exception), while heapify is what establishes the heap invariants in the first place...

Alex Martelli
Both heapify-versions (using siftUp or siftDown) consider only a part of the array as "already heapified" and call siftUp/Down accordingly: $a = siftDown($a, $start, $count-1), instead of siftDown($a, 0, $end); which is used during the actual sort.
VolkerK
+2  A: 
VolkerK
Ok, thanks, that did the trick.
Ron