forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinearSearch.php
35 lines (33 loc) · 841 Bytes
/
LinearSearch.php
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
<?php
/**
* Linear search in PHP
*
* Reference: https://www.geeksforgeeks.org/linear-search/
*
* @param Array $list a array of integers to search
* @param integer $target an integer number to search for in the list
* @return integer the index where the target is found (or -1 if not found)
*
* Examples:
* data = 5, 7, 8, 11, 12, 15, 17, 18, 20
* x = 15
* Element found at position 6
*
* x = 1
* Element not found
*
* @param Array $list a array of integers to search
* @param integer $target an integer number to search for in the list
* @return integer the index where the target is found (or -1 if not found)
*/
function linearSearch($list, $target)
{
$n = sizeof($list);
for($i = 0; $i < $n; $i++)
{
if($list[$i] == $target) {
return $i + 1;
}
}
return -1;
}