<?php

//array(g, x, y, f, h)
//where
//h = heuristic
//f = cost from start
//g = sum


echo "heap";
$t = array();
$t = heap_push($t,array(4,0,0,0,0));
$t = heap_push($t,array(2,0,0,0,0));
$t = heap_push($t,array(6,0,0,0,0));
$t = heap_push($t,array(1,0,0,0,0));
$t = heap_push($t,array(3,0,0,0,0));
$t = heap_push($t,array(5,0,0,0,0));
$t = heap_push($t,array(7,0,0,0,0));
heap_show($t);
$t = heap_pop($t);
heap_show($t);


function heap_show($a)
{
    foreach($a as $i)
    {
        echo 'g' . $i[0] . 'x' . $i[1] . 'y' . $i[2] . 'f' . $i[3] . ' ';
    }
    echo "<br />";
}

function heap_cmp($i,$j)
{
    if($i[0] < $j[0])
    {
        return TRUE;
    }
    return FALSE;
}

/*function*/

function heapfy($a)
{
    for($i=1;$i<sizeof($a);$i++)
    {
        $c = $i;
        while($c>0)
        {
            $p = ($c-1)/2;      //parent
            if(heap_cmp($a[$c],$a[$p])==TRUE)
            {
                //swap
                $tmp = $a[$p];
                $a[$p] = $a[$c];
                $a[$c] = $tmp;
            }
            $c = $p;
        }
    }
    return $a;
}

function heap_push($a,$x)
{
    $a[] = $x;
    $c = sizeof($a)-1;
    while($c>0)
    {
        $p = ($c-1)/2;      //parent
        if(heap_cmp($a[$c], $a[$p])==TRUE)
        {
            //swap
            $tmp = $a[$p];
            $a[$p] = $a[$c];
            $a[$c] = $tmp;
        }
        $c = $p;
    }
    return $a;
}

function heap_pop($a)
{
    if(sizeof($a)<2)
    {
        return array();
    }
    $r = $a[0];
    $a[0] = array_pop($a);
    $p = 0;
    $s = sizeof($a);
    $c = ($p*2)+1;      //left
    while($c<$s)
    {
        $r = ($p*2)+2;      //right
        if(($r < $s)and(heap_cmp($a[$r],$a[$c])==TRUE))
        {
            $c = $r;
        }
        if(heap_cmp($a[$c],$a[$p])==TRUE)
        {
            //swap
            $tmp = $a[$c];
            $a[$c] = $a[$p];
            $a[$p] = $tmp;
        }
        $p = $c;
        $c = ($p*2)+1;      //left
    }
    return $a; 
}

?>
