Merge function working correctly.I have 2 queries in merge sort 1) I am not able to get why "merge" function calls third time(print execute) here when count==1 condition mets two times for both left and right together. 2) If I comment return $x then printing $x shows blank array third time otherwise $x show sorted array in third time why?
$arr= array(4,2,7,5);
$count= count($arr);
//Merge Sort
$result= merging($arr);
//echo "<pre>"; print_r($result); exit;
function merging($arr)
{
$count= count($arr);
if($count==1){ return $arr; }
$mid= ceil($count/2);
$left= array_slice($arr,0,$mid);
$right= array_slice($arr,$mid);
$left= merging($left);
$right= merging($right);
echo "execute";
$x= merge($left,$right);
echo "<pre>"; print_r($x); //exit;
//return $x;
}
function merge($left,$right)
{
//echo "<pre>"; print_r($left);
//echo "<pre>"; print_r($right);
$l=0; $r=0; $temp=[];
while($l<count($left) && $r<count($right))
{
if($left[$l]> $right[$r])
{
$temp[]= $right[$r];
$r++;
}else{
$temp[]= $left[$l];
$l++;
}
}
while($l < count($left))
{
$temp[]= $left[$l];
$l++;
}
while($r < count($right))
{
$temp[]= $right[$r];
$r++;
}
return $temp;
}