The Linear Search algorithm is a basic and straightforward search method. It works by iterating through each element of a sequence to find a specific value. While simple, this method is effective for small sequences or when the sequence is already sorted.
How It Works
- Iterate Through Elements: Start from the first element and check if the current value matches the target value.
- Check for Match: If the value at the current position matches the target value, the search process ends, and the position of the value is returned.
- Move to Next Element: If no match is found, move to the next element and continue checking.
- Repeat: Repeat steps 2 and 3 until the value is found or the entire sequence is traversed.
Example: Linear Search for the Number 7 in an Array
function linearSearch($arr, $target) {
$n = count($arr);
for ($i = 0; $i < $n; $i++) {
if ($arr[$i] == $target) {
return $i; // Return the position of the value
}
}
return -1; // Value not found
}
$array = [2, 5, 8, 12, 15, 7, 20];
$targetValue = 7;
$result = linearSearch($array, $targetValue);
if ($result != -1) {
echo "Value $targetValue found at position $result.";
} else {
echo "Value $targetValue not found in the array.";
}
In this example, we use the Linear Search method to find the value 7 in the given array. We iterate through each element of the array and compare it with the target value. When we find the value 7 at the 5th position, the program returns the message "Value 7 found at position