Created
January 3, 2020 14:32
-
-
Save wajdijurry/fe02c6a5870fb180a2788f509fd0f284 to your computer and use it in GitHub Desktop.
Find a number within an array in recursive mode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Find a number within an array in recursive mode | |
*/ | |
function findNumber($a, $num, $start, $end) { | |
$mid = floor(($end - $start) / 2) + $start; | |
if ($num > $a[$end] || $num < $a[0] || $start > $end) { | |
return "number does not exist"; | |
} | |
if ($a[$mid] == $num) { | |
return $mid; | |
} elseif ($a[$mid] < $num) { | |
return findNumber($a, $num, $mid+1, $end); | |
} else { | |
return findNumber($a, $num, $start, $mid-1); | |
} | |
} | |
$a = [1, 2, 3, 4, 5, 6, 7, 8]; | |
echo findNumber($a, 1, 0, count($a)-1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment