Skip to content

Instantly share code, notes, and snippets.

@firomero
Created August 28, 2015 12:51
Show Gist options
  • Select an option

  • Save firomero/831397bbf9f05bb083e8 to your computer and use it in GitHub Desktop.

Select an option

Save firomero/831397bbf9f05bb083e8 to your computer and use it in GitHub Desktop.
Uncentered Binary Search
/**
* Binary Search Uncentered
* This is the method of binary search calculating the exact pivote for the search.
* @param array $haystack
* @param $first
* @param $last
* @param $needle
* @return bool
*/
function binary_search_uncentered(array $haystack, $first, $last,$needle){
$nterc = round(sizeof($haystack)/3);
if ($first>=$last) {
if ($haystack[$last]==$needle) {
return true;
} else {
return false;
}
}
$nterc = round(($last-$first+1)/3);
if ($needle==$haystack[$first+$nterc]) {
return true;
}elseif($needle<$haystack[$first+$nterc]){
return binary_search_uncentered($haystack,$first,$first+$nterc-1,$needle);
} elseif ($needle==$haystack[$last-$nterc]) {
return true;
} elseif ($needle<$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