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?

4

3 回答 3

2

siftDown() 应该改变你传入的数组。因此你必须通过引用传递它。否则,该函数将对数据的副本进行操作。

function siftDown(&$a, $start, $end) {
于 2009-06-23T05:20:09.617 回答
1

我认为这是php中堆排序的最简单代码

于 2011-06-08T11:44:17.800 回答
0

我不是 PHP 专家,但似乎heapify做得不对——堆化如何归结为一堆对 siftDown 的调用......?后者是假设它正在处理一个是堆的数组(可能有一个例外),而heapify这是首先建立堆不变量的原因......

于 2009-06-23T05:11:20.753 回答