mirror of
https://github.com/TheAlgorithms/PHP.git
synced 2025-01-17 15:18:13 +01:00
8389d29c76
* Create SentinelSearch.php Added Sentinel Search algorithm in Searches folder * Update SentinelSearch.php * Update SearchesTest.php Added tests for SentinelSearch.php * Update DIRECTORY.md Added link for sentinel search * Update SearchesTest.php Testcase corrected * Updated SentinelSearch.php * Updated SearchesTest.php * Update Searches/SentinelSearch.php * Update Searches/SentinelSearch.php * Update Searches/SentinelSearch.php * Update Searches/SentinelSearch.php * Update Searches/SentinelSearch.php * Update Searches/SentinelSearch.php * Update Searches/SentinelSearch.php --------- Co-authored-by: Brandon Johnson <bbj1979@gmail.com>
43 lines
927 B
PHP
43 lines
927 B
PHP
<?php
|
|
|
|
/* SentinelSearch
|
|
Input : -
|
|
parameter 1: Array
|
|
parameter 2: Target element
|
|
|
|
Output : -
|
|
Returns index of element if found, else -1
|
|
*/
|
|
function SentinelSearch($list, $target)
|
|
{
|
|
//Length of array
|
|
$len = sizeof($list);
|
|
|
|
//Store last element of array
|
|
$lastElement = $list[$len - 1];
|
|
|
|
//Put target at the last position of array known as 'Sentinel'
|
|
if ($lastElement == $target) {
|
|
return ($len - 1);
|
|
}
|
|
//Put target at last index of array
|
|
$list[$len - 1] = $target;
|
|
|
|
//Initialize variable to traverse through array
|
|
$i = 0;
|
|
|
|
//Traverse through array to search target
|
|
while ($list[$i] != $target) {
|
|
$i++;
|
|
}
|
|
//Put last element at it's position
|
|
$list[$len - 1] = $lastElement;
|
|
|
|
//If i in less than length, It means element is present in array
|
|
if ($i < ($len - 1)) {
|
|
return $i;
|
|
} else {
|
|
return -1;
|
|
}
|
|
}
|