gpt4 book ai didi

php - 在我的堆排序方面需要帮助

转载 作者:行者123 更新时间:2023-12-04 07:06:47 24 4
gpt4 key购买 nike

我有点坚持我在 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);
?>

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

最佳答案

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

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

关于php - 在我的堆排序方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1030694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com