forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create SentinelSearch.php (TheAlgorithms#124)
* 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 <[email protected]>
- Loading branch information
1 parent
5d9350b
commit 8389d29
Showing
3 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
<?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; | ||
} | ||
} |
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