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,26 @@
<?php
function findSmall(array $arr)
{
$smallest = $arr[0];
$smallestIndex = 0;
for ($i = 0; $i < count($arr); $i++) {
if ($arr[$i] < $smallest) {
$smallest = $arr[$i];
$smallestIndex = $i;
}
}
return $smallestIndex;
}
function selectionSort(array $arr)
{
$newArr = [];
for ($i = 0, $length = count($arr); $i < $length; $i++) {
$smallest = findSmall($arr);
array_push($newArr, array_splice($arr, $smallest, 1)[0]);
}
return $newArr;
}
var_dump(selectionSort([5, 3, 6, 2, 10])); // [2, 3, 5, 6, 10]

View File

@@ -0,0 +1,14 @@
<?php
function countdown($i)
{
echo $i;
// base case
if ($i <= 0) {
return;
} else {
countdown($i - 1);
}
}
countdown(5);

View File

@@ -0,0 +1,21 @@
<?php
function greet2($name)
{
echo 'how are you, ' . $name . '?';
}
function bye()
{
echo 'ok bye!';
}
function greet($name)
{
echo 'hello, ' . $name . '!';
greet2($name);
echo 'getting ready to say bye...';
bye();
}
greet('adit');

View File

@@ -0,0 +1,11 @@
<?php
function fact($x)
{
if ($x === 1) {
return 1;
}
return $x * fact($x - 1);
}
echo fact(5);

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]