Last active
May 6, 2020 20:57
-
-
Save aran112000/984831c37212f6da163057b2787adb2e to your computer and use it in GitHub Desktop.
Example of a simple function to perform a Binary Search in PHP to search for a String value
This file contains 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 | |
/** | |
* @param string $value The value you're searching for | |
* @param array $dataSet Your sorted data set to search | |
* | |
* @return int Returns the key matched, or -1 if no match is found | |
*/ | |
function binarySearchString(string $value, array $dataSet): int | |
{ | |
$start = 0; | |
$end = count($dataSet) - 1; | |
while ($start <= $end) { | |
$middle = intdiv($end, 2); | |
if ($value === $dataSet[$middle]) { | |
return $middle; | |
} | |
if (strcmp($value, $dataSet[$middle]) < 0) { | |
$end = $middle + 1; | |
continue; | |
} | |
$start = $middle - 1; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment