AleRemote225 AleRemote225 - 19 days ago 4
PHP Question

PHP: Quick sort code keeps saying: Warning: array_merge(): Argument #3 is not an array in

I am learning about sorting algorithms and I am trying this code:

function quicksort($array){
if(count($array) == 0){
return array();
}

$pivot = $array[0];
$left = array();
$right = array();

for($i = 1; $i < count($array); $i++){
if($array[$i] < $pivot){
$left[] = $array[$i];
}
else{
$right[] = $array[$i];
}

return array_merge(quicksort($left), array($pivot), quicksort($right));
}

}
$sorted = quicksort($data);


However, when trying to run it - it gives me:


Warning: array_merge(): Argument #3 is not an array in - on line 21


Any reason for this?

Answer

you're returning inside the loop, you need to move that statement outside the loop.

<?php
function quicksort($array){
    if(count($array) == 0){
        return array();
    }

    $pivot = $array[0];
    $left = array();
    $right = array();

    for($i = 1; $i < count($array); $i++){
        if($array[$i] < $pivot){
            $left[] = $array[$i];
        }
        else{
            $right[] = $array[$i];
        }
        // remove return that was here
    }

    // and move it outside the loop here
    return array_merge(quicksort($left), array($pivot), quicksort($right));
}

$data = [3,4,2,1];
print_r(quicksort($data));
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Comments