forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSentinelSearch.php
More file actions
42 lines (35 loc) · 927 Bytes
/
SentinelSearch.php
File metadata and controls
42 lines (35 loc) · 927 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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;
}
}