TheAlgorithms-PHP/Searches/JumpSearch.php

40 lines
1000 B
PHP
Raw Normal View History

2022-08-03 10:01:55 +08:00
<?php
2022-08-03 10:01:55 +08:00
/**
* Jump Search algorithm in PHP
* References: https://www.geeksforgeeks.org/jump-search/
* The list must be sorted in ascending order before performing jumpSearch
*
* @param Array $list refers to a sorted list of integer
2022-08-03 10:01:55 +08:00
* @param integer $key refers to the integer target to be searched from the sorted list
* @return int index of $key if found, otherwise -1 is returned
2022-08-03 10:01:55 +08:00
*/
function jumpSearch($list, $key)
{
/*number of elements in the sorted array*/
$num = count($list);
2023-10-05 09:59:11 +03:30
/*block size to be jumped*/
$step = (int)sqrt($num);
$prev = 0;
2022-08-03 10:01:55 +08:00
while ($list[min($step, $num) - 1] < $key) {
$prev = $step;
$step += (int)sqrt($num);
if ($prev >= $num) {
return -1;
}
}
2022-08-03 10:01:55 +08:00
/*Performing linear search for $key in block*/
while ($list[$prev] < $key) {
$prev++;
if ($prev == min($step, $num)) {
return -1;
}
}
2022-08-03 10:01:55 +08:00
return $list[$prev] === $key ? $prev : -1;
}