function quick($a) {
if (count($a) < 2) return $a;
$l = [];
$r = [];
$pivot = $a[0];
foreach ($a as $val) {
if ($val > $pivot) {
$r[] = $val;
} else {
$l[] = $val;
}
}
return array_merge(quick($l), [$pivot], quick($r));
}
print_r(quick($a));
I get this error:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /Applications/XAMPP/xamppfiles/htdocs/sort.php on line 46
Line 46 is $l[] = $val;
Quite simple. You're getting nearly infinite recursion.
The reason is that you're not excluding the pivot point from the sub-arrays. So $l
will always contain it. And if $pivot
is not the smallest value in the array, you'll infinitely recurse with an empty $r
array, and copying $a
into $l
...
Instead, you need to adjust your if condition and look at the pivot key:
$pivot = $a[0];
foreach ($a as $key => $val) {
if ($key === 0) {
continue; // pivot
} elseif ($val > $pivot) {
$r[] = $val;
} else {
$l[] = $val;
}
}