(Linear Search) PHP 中的 线性搜索算法- 解释、示例和代码

线性搜索算法是一种基本且直接的搜索方法。 它的工作原理是迭代序列的每个元素以查找特定值。 虽然简单,但此方法对于小序列或序列已排序时非常有效。

怎么运行的

  1. 迭代元素: 从第一个元素开始,检查当前值是否与目标值匹配。
  2. 检查匹配: 如果当前位置的值与目标值匹配,则搜索过程结束,并返回该值的位置。
  3. 移至下一个元素: 如果未找到匹配项,则移至下一个元素并继续检查。
  4. 重复: 重复步骤2和3,直到找到该值或遍历整个序列。

示例:线性搜索数组中的数字 7

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.";  
}  

在此示例中,我们使用线性搜索方法在给定数组中查找值 7。 我们迭代数组的每个元素并将其与目标值进行比较。 当我们在第 5 个位置找到值 7 时,程序返回消息“在位置找到值 7