Created
August 28, 2015 12:53
-
-
Save firomero/6d0a8ee9c00d6ba1060b to your computer and use it in GitHub Desktop.
Binary Search Uncentered Callback
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
/** | |
* Binary Search Uncentered with Callback | |
* This is the method of binary search calculating the exact pivote for the search. | |
* @param array $haystack | |
* @param $first | |
* @param $last | |
* @param $needle | |
* @param callable $callback | |
* @return bool | |
*/ | |
function binary_search_uncentered_callable(array $haystack, $first, $last,$needle, callable $callback){ | |
$nterc = round(sizeof($haystack)/3); | |
if ($first>=$last) { | |
if ($callback($haystack[$last])==$callback($needle)) { | |
return $last; | |
} else { | |
return -1; | |
} | |
} | |
$nterc = round(($last-$first+1)/3); | |
if ($callback($needle)==$callback($haystack[$first+$nterc])) { | |
return $first+$nterc; | |
}elseif($callback($needle)<$callback($haystack[$first+$nterc])){ | |
return binary_search_uncentered($haystack,$first,$first+$nterc-1,$needle); | |
} elseif ($callback($needle)==$callback($haystack[$last-$nterc])) { | |
return $last-$nterc; | |
} elseif ($callback($needle)<$callback($haystack[$last-$nterc])) { | |
return binary_search_uncentered($haystack,$first+$nterc+1,$last-$nterc-1,$needle); | |
} else { | |
return binary_search_uncentered($haystack,$last-$nterc+1,$last,$needle); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment