搜尋演算法是程式設計基礎。本文實作 循序搜尋 (Linear Search) 與 二分搜尋 (Binary Search),分析時間複雜度、適用場景,並提供可直接使用的 PHP 類別封裝。
適用於未排序、小規模資料集,或需找出所有符合項目的情況。
<?php
class Search
{
private array $data;
public function __construct(array $data)
{
$this->data = $data;
}
// 循序搜尋:回傳第一個符合的索引,找不到回傳 -1
public function linearSearch(mixed $target): int
{
foreach ($this->data as $index => $value) {
if ($value === $target) {
return $index;
}
}
return -1;
}
// 循序搜尋所有符合項目
public function linearSearchAll(mixed $target): array
{
$indices = [];
foreach ($this->data as $index => $value) {
if ($value === $target) {
$indices[] = $index;
}
}
return $indices;
}
}
前提:資料必須已排序。時間複雜度 O(log n),大幅優於循序搜尋的 O(n)。
<?php
class Search
{
// ... (上述建構子與 linearSearch)
// 二分搜尋:回傳找到的索引,找不到回傳 -1
public function binarySearch(mixed $target): int
{
$data = $this->data;
sort($data, SORT_REGULAR); // 確保已排序 (副本排序不影響原陣列)
// 若確定外部已排序,可移除此行並直接使用 $this->data
$low = 0;
$high = count($data) - 1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
$midVal = $data[$mid];
if ($midVal === $target) {
return $mid; // 找到
} elseif ($target < $midVal) {
$high = $mid - 1; // 搜尋左半部
} else {
$low = $mid + 1; // 搜尋右半部
}
}
return -1; // 未找到
}
// 遞迴版本
public function binarySearchRecursive(mixed $target, int $low = 0, int $high = null): int
{
$data = $this->data;
if ($high === null) {
sort($data);
$high = count($data) - 1;
}
if ($low > $high) return -1;
$mid = (int)(($low + $high) / 2);
if ($data[$mid] === $target) return $mid;
return $target < $data[$mid]
? $this->binarySearchRecursive($target, $low, $mid - 1)
: $this->binarySearchRecursive($target, $mid + 1, $high);
}
}
<?php
require 'Search.php';
// 建立 100,000 筆測試資料
$data = range(1, 100000);
shuffle($data); // 打亂順序
$search = new Search($data);
$target = 50000;
// 循序搜尋測試
$start = microtime(true);
$idx1 = $search->linearSearch($target);
$time1 = microtime(true) - $start;
// 二分搜尋測試 (需排序)
$start = microtime(true);
$idx2 = $search->binarySearch($target);
$time2 = microtime(true) - $start;
echo "目標: $target\n";
echo "循序搜尋: 索引 $idx1, 耗時 " . number_format($time1 * 1000, 4) . " ms\n";
echo "二分搜尋: 索引 $idx2, 耗時 " . number_format($time2 * 1000, 4) . " ms\n";
echo "加速比: " . number_format($time1 / $time2, 1) . "x\n";
// 典型輸出:
// 循序搜尋: 索引 49999, 耗時 2.3456 ms
// 二分搜尋: 索引 49999, 耗時 0.0123 ms
// 加速比: 190.7x
| 演算法 | 時間複雜度 | 空間複雜度 | 前提條件 | 最佳場景 |
|---|---|---|---|---|
| 循序搜尋 | O(n) | O(1) | 無 | 未排序、小資料集、需找所有匹配、串流資料 |
| 二分搜尋 (迭代) | O(log n) | O(1) | 已排序 | 大型已排序陣列、頻繁查詢、靜態資料 |
| 二分搜尋 (遞迴) | O(log n) | O(log n) | 已排序 | 教學示範、函數式風格、尾遞迴優化語言 |
// 找第一個 >= target 的位置 (lower_bound)
public function lowerBound(mixed $target): int
{
$data = $this->data; sort($data);
$low = 0; $high = count($data);
while ($low < $high) {
$mid = (int)(($low + $high) / 2);
if ($data[$mid] < $target) $low = $mid + 1;
else $high = $mid;
}
return $low; // 可能等於 count($data) 表示所有元素都 < target
}
// 找第一個 > target 的位置 (upper_bound)
public function upperBound(mixed $target): int
{
$data = $this->data; sort($data);
$low = 0; $high = count($data);
while ($low < $high) {
$mid = (int)(($low + $high) / 2);
if ($data[$mid] <= $target) $low = $mid + 1;
else $high = $mid;
}
return $low;
}
// 計算目標值出現次數
public function countOccurrences(mixed $target): int
{
return $this->upperBound($target) - $this->lowerBound($target);
}
<?php
$data = [1, 3, 5, 7, 9, 11, 13];
// array_search - 循序搜尋 (未排序適用)
$key = array_search(7, $data); // 3
// in_array - 檢查存在性
$exists = in_array(7, $data); // true
// 二分搜尋需自行實作或使用第三方庫
// PHP 核心無內建 binary_search,但可用 spl_fixedarray 或擴充