Created
January 16, 2018 20:59
-
-
Save CaroManel/12c831d347eb978f1f9576a42a4ff0c8 to your computer and use it in GitHub Desktop.
Jump 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 JumpSearch($list, $find) | |
{ | |
$len = count($list) ; | |
$slice = floor(sqrt($len)); | |
$prev = 0; | |
while ($list[min($slice, $len)] < $find || $prev >= $len) { | |
$prev = $slice; | |
$slice += floor(sqrt($len)); | |
} | |
while ($list[$prev] < $find || $prev == $len) { | |
$prev++; | |
if ($prev == $slice) { | |
break; | |
} | |
} | |
if ( $list[$prev] == $find) { | |
return $prev; | |
} | |
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 = 71; | |
$result = JumpSearch($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