| 演算法 | 前提條件 | 時間複雜度 | 空間複雜度 | 適用場景 |
|---|---|---|---|---|
| 循序搜尋 | 無序/有序皆可 | O(n) | O(1) | 小資料集、單次搜尋 |
| 二分搜尋 | **必須已排序** | O(log n) | O(1) | 大型有序資料、頻繁搜尋 |
<?php
/**
* 循序搜尋
* @param array $arr 搜尋陣列
* @param mixed $target 目標值
* @return int|false 找到返回索引,否則 false
*/
function linearSearch(array $arr, $target)
{
foreach ($arr as $index => $value) {
if ($value === $target) {
return $index;
}
}
return false;
}
// 測試
$data = [1, 2, 3, 5, 7, 6, 4, 8];
var_dump(linearSearch($data, 5)); // int(3)
var_dump(linearSearch($data, 9)); // bool(false)
?>
<?php
/**
* 二分搜尋 (迭代實作)
* @param array $arr **已排序** 陣列
* @param mixed $target 目標值
* @return int|false 找到返回索引,否則 false
*/
function binarySearch(array $arr, $target)
{
$low = 0;
$high = count($arr) - 1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
$midVal = $arr[$mid];
if ($midVal === $target) {
return $mid;
} elseif ($midVal < $target) {
$low = $mid + 1;
} else {
$high = $mid - 1;
}
}
return false;
}
// 測試 (資料必須先排序)
$sortedData = [1, 2, 3, 4, 5, 6, 7, 8];
var_dump(binarySearch($sortedData, 5)); // int(4)
var_dump(binarySearch($sortedData, 9)); // bool(false)
?>
<?php
function binarySearchRecursive(array $arr, $target, int $low = 0, int $high = null)
{
if ($high === null) $high = count($arr) - 1;
if ($low > $high) return false;
$mid = (int)(($low + $high) / 2);
if ($arr[$mid] === $target) return $mid;
if ($arr[$mid] < $target) return binarySearchRecursive($arr, $target, $mid + 1, $high);
return binarySearchRecursive($arr, $target, $low, $mid - 1);
}
?>
<?php $arr = [1, 2, 3, 4, 5, 6, 7, 8]; // array_search - 循序搜尋 (嚴格模式) $key = array_search(5, $arr, true); // 4 // 在有序陣列二分搜尋無內建函數,但可用二分查找庫或自行實作 // 陣列去重 + 排序 + 搜尋組合 $uniqueSorted = array_values(array_unique($arr)); sort($uniqueSorted); ?>
<?php $data = range(1, 1_000_000); $target = 999_999; $start = microtime(true); linearSearch($data, $target); echo "循序搜尋: " . (microtime(true) - $start) . " 秒\n"; // ~0.03s $start = microtime(true); binarySearch($data, $target); echo "二分搜尋: " . (microtime(true) - $start) . " 秒\n"; // ~0.00001s ?>
$map[$key]WHERE 條件 + 索引優化選對演算法,是效能優化的第一步。