Created
January 16, 2018 21:17
-
-
Save CaroManel/334fc1401be7ce596d7399aeb25bfb0e to your computer and use it in GitHub Desktop.
Interpolation Search
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 | |
function interpolationSearch($list, $find) | |
{ | |
$low = 0; | |
$high = count($list) - 1; | |
while ($low <= $high && $find >= $list[$low] && $find <= $list[$high]) { | |
$pos = floor($low + (($high-$low) / | |
($list[$high]-$list[$low])) * ($find - $list[$low])); | |
if ($list[$pos] == $find){ | |
return $pos; | |
} | |
if ($list[$pos] < $find){ | |
$low = $pos + 1; | |
} else{ | |
$high = $pos - 1; | |
} | |
} | |
return -1; | |
} | |
$array = [2,4,5,7,8,13,14,15,26,27,29,31,44,45,46,66,67,68,69,71,80]; | |
$find = 66; | |
$result = interpolationSearch($array, $find); | |
echo "Found $find at index $result"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment