萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 循序搜尋與二分搜尋演算法實作與效能分析

搜尋演算法是程式設計基礎。本文實作 循序搜尋 (Linear Search) 與 二分搜尋 (Binary Search),分析時間複雜度、適用場景,並提供可直接使用的 PHP 類別封裝。

循序搜尋 (Linear Search)

適用於未排序、小規模資料集,或需找出所有符合項目的情況。

<?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;
    }
}

二分搜尋 (Binary Search)

前提:資料必須已排序。時間複雜度 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)已排序教學示範、函數式風格、尾遞迴優化語言

進階變體

1. 下界/上界搜尋 (Lower/Upper Bound)


// 找第一個 >= 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);
}

2. 陣列內建函式 (實務首選)

<?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 或擴充

實務建議

  • 資料量 < 50:循序搜尋足夠,程式碼簡單
  • 靜態資料、頻繁查詢:預先排序 + 二分搜尋
  • 動態資料、頻繁增刪:考慮 平衡樹 (AVL/Red-Black)、B+ 樹、資料庫索引、Elasticsearch
  • 關聯式查詢:直接用 SQL `WHERE` + 索引,勿在 PHP 層搜尋
copyright © 萬盛學電腦網 all rights reserved