Precisa de ajuda com a minha pilha de tipo
Pergunta
Eu sou o tipo de preso com a minha pilha tipo aqui em 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);
?>
Eu não posso começar a classificar a matriz, alguma idéia do que está errado?
Solução
siftDown () é suposto para alterar a matriz que você passar. Portanto, você tem que passá-lo por referência. Caso contrário, a função irá operar em uma cópia dos dados.
function siftDown(&$a, $start, $end) {
Outras dicas
Eu acho que este é o código mais simples para pilha Classificar em php
Não sou especialista PHP, mas não parece ser heapify
é bem feito - como pode heapification resumem a um monte de chamadas para siftDown ...? Este último é escrito assumindo que é lidar com uma matriz que é um amontoado (com possivelmente uma exceção), enquanto heapify
é o que estabelece as invariantes heap em primeiro lugar ...