Adding PHP examples

This commit is contained in:
vendin
2017-09-21 00:00:43 +03:00
committed by Aditya Bhargava
parent 8ec4dc010b
commit 495a648a6a
9 changed files with 137 additions and 0 deletions

View 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

View 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

View 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

View 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

View 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]