TheAlgorithms-PHP/searches/linear_search.php

47 lines
909 B
PHP
Raw Normal View History

2020-10-04 00:07:19 +05:30
<?php
2020-10-13 11:00:41 +05:30
/**
* 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:
*
2020-10-13 11:01:52 +05:30
* data = 5, 7, 8, 11, 12, 15, 17, 18, 20
2020-10-13 11:00:41 +05:30
*
* x = 15
* Element found at position 6
*
* x = 1
* Element not found
*
**/
function linear_search($list, $target) #Linear Search
2020-10-04 00:07:19 +05:30
{ $n = sizeof($list);
for($i = 0; $i < $n; $i++)
{
if($list[$i] == $target)
2020-10-13 11:00:41 +05:30
return $i+1;
2020-10-04 00:07:19 +05:30
}
return -1;
}
2020-10-13 11:00:41 +05:30
# DRIVER CODE
2020-10-24 00:19:36 +05:30
$data = array(5, 7, 8, 11, 12, 15, 17, 18, 20);
2020-10-04 00:07:19 +05:30
$x = 15;
2020-10-13 11:00:41 +05:30
$result = linear_search($data, $x); # OUTPUT DISPLAY
2020-10-04 00:07:19 +05:30
if($result == -1)
echo "Element not found";
else
echo "Element found at position " , $result;
?>