Adding PHP examples
This commit is contained in:
12
04_quicksort/php/01_loop_sum.php
Normal file
12
04_quicksort/php/01_loop_sum.php
Normal file
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
function sum(array $arr)
|
||||
{
|
||||
$total = 0;
|
||||
for ($x = 0; $x < count($arr); $x++) {
|
||||
$total += $arr[$x];
|
||||
}
|
||||
return $total;
|
||||
}
|
||||
|
||||
echo sum([1, 2, 3, 4]); // 10
|
||||
11
04_quicksort/php/02_recursive_count.php
Normal file
11
04_quicksort/php/02_recursive_count.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
function sum($list)
|
||||
{
|
||||
if (count($list) === 0) {
|
||||
return 0;
|
||||
}
|
||||
return $list[0] + sum(array_splice($list, 1));
|
||||
}
|
||||
|
||||
echo sum([1, 2, 3, 4]); // 10
|
||||
10
04_quicksort/php/03_recursive_count.php
Normal file
10
04_quicksort/php/03_recursive_count.php
Normal file
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
function recursiveCount($list) {
|
||||
if (count($list) === 0) {
|
||||
return 0;
|
||||
}
|
||||
return 1 + recursiveCount(array_splice($list, 1));
|
||||
}
|
||||
|
||||
echo count([0, 1, 2, 3, 4, 5]); // 6
|
||||
11
04_quicksort/php/04_recursive_max.php
Normal file
11
04_quicksort/php/04_recursive_max.php
Normal file
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
function recursiveMax($list) {
|
||||
if (count($list) === 2) {
|
||||
return $list[0] > $list[1] ? $list[0] : $list[1];
|
||||
}
|
||||
$subMax = recursiveMax(array_splice($list, 1));
|
||||
return $list[0] > $subMax ? $list[0] : $subMax;
|
||||
}
|
||||
|
||||
echo recursiveMax([1, 5, 10, 25, 16, 1]); // 25
|
||||
21
04_quicksort/php/05_quicksort.php
Normal file
21
04_quicksort/php/05_quicksort.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
function quicksort(array $array) {
|
||||
if (count($array) < 2) {
|
||||
// base case, arrays with 0 or 1 element are already "sorted"
|
||||
return $array;
|
||||
} else {
|
||||
// recursive case
|
||||
$pivot = $array[0];
|
||||
var_dump($array);
|
||||
|
||||
// sub-array of all the elements less than the pivot
|
||||
$less = array_filter(array_slice($array, 1), function($el) use ($pivot) { return $el <= $pivot; });
|
||||
|
||||
// sub-array of all the elements greater than the pivot
|
||||
$greater = array_filter(array_slice($array, 1), function($el) use ($pivot) { return $el > $pivot; });
|
||||
return array_merge(quicksort($less), [$pivot], quicksort($greater));
|
||||
}
|
||||
}
|
||||
|
||||
var_dump(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]
|
||||
Reference in New Issue
Block a user