需要帮助我的堆排序

时间:2009-06-23 05:02:31

标签: php sorting heap

我在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);
    ?>

我无法对数组进行排序,不知道出了什么问题?

3 个答案:

答案 0 :(得分:2)

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

function siftDown(&$a, $start, $end) {

答案 1 :(得分:1)

我认为这是 heap Sort in php

最简单的代码

答案 2 :(得分:0)

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