PHP 常用算法

PHP 常用算法

排序算法

1. 冒泡排序

function bubbleSort($array) {
    $n = count($array);
    for ($i = 0; $i < $n - 1; $i++) {
        for ($j = 0; $j < $n - $i - 1; $j++) {
            if ($array[$j] > $array[$j + 1]) {
                // 交换元素
                $temp = $array[$j];
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;
            }
        }
    }
    return $array;
}

2. 快速排序

function quickSort($array) {
    if (count($array) <= 1) {
        return $array;
    }
    
    $pivot = $array[0];
    $left = $right = array();
    
    for ($i = 1; $i < count($array); $i++) {
        if ($array[$i] < $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }
    }
    
    return array_merge(quickSort($left), array($pivot), quickSort($right));
}

搜索算法

1. 二分查找

function binarySearch($array, $target) {
    $left = 0;
    $right = count($array) - 1;
    
    while ($left <= $right) {
        $mid = floor(($left + $right) / 2);
        
        if ($array[$mid] == $target) {
            return $mid;
        }
        
        if ($array[$mid] < $target) {
            $left = $mid + 1;
        } else {
            $right = $mid - 1;
        }
    }
    
    return -1; // 未找到
}

字符串算法

1. 字符串反转

function reverseString($str) {
    $length = strlen($str);
    $reversed = '';
    
    for ($i = $length - 1; $i >= 0; $i--) {
        $reversed .= $str[$i];
    }
    
    return $reversed;
}

2. 判断回文字符串

function isPalindrome($str) {
    $str = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str));
    return $str == strrev($str);
}

数学算法

1. 斐波那契数列

function fibonacci($n) {
    if ($n <= 1) {
        return $n;
    }
    
    $a = 0;
    $b = 1;
    
    for ($i = 2; $i <= $n; $i++) {
        $c = $a + $b;
        $a = $b;
        $b = $c;
    }
    
    return $b;
}

2. 判断素数

function isPrime($num) {
    if ($num <= 1) {
        return false;
    }
    
    for ($i = 2; $i <= sqrt($num); $i++) {
        if ($num % $i == 0) {
            return false;
        }
    }
    
    return true;
}

数组算法

1. 数组去重

function removeDuplicates($array) {
    return array_values(array_unique($array));
}

2. 寻找数组中的最大值和最小值

function findMinMax($array) {
    $min = $max = $array[0];
    
    foreach ($array as $value) {
        if ($value < $min) {
            $min = $value;
        }
        if ($value > $max) {
            $max = $value;
        }
    }
    
    return ['min' => $min, 'max' => $max];
}

图算法

1. 广度优先搜索 (BFS)

function bfs($graph, $start) {
    $visited = [];
    $queue = new SplQueue();
    
    $queue->enqueue($start);
    $visited[$start] = true;
    
    while (!$queue->isEmpty()) {
        $vertex = $queue->dequeue();
        echo $vertex . " ";
        
        foreach ($graph[$vertex] as $neighbor) {
            if (!isset($visited[$neighbor])) {
                $visited[$neighbor] = true;
                $queue->enqueue($neighbor);
            }
        }
    }
}

递归算法

1. 阶乘计算

function factorial($n) {
    if ($n <= 1) {
        return 1;
    }
    return $n * factorial($n - 1);
}

2. 汉诺塔问题

function hanoi($n, $from, $to, $via) {
    if ($n == 1) {
        echo "Move disk 1 from $from to $to\n";
    } else {
        hanoi($n - 1, $from, $via, $to);
        echo "Move disk $n from $from to $to\n";
        hanoi($n - 1, $via, $to, $from);
    }
}

动态规划算法

1. 斐波那契数列(动态规划版)

function fibonacciDP($n) {
    if ($n <= 1) {
        return $n;
    }
    
    $dp = [0, 1];
    for ($i = 2; $i <= $n; $i++) {
        $dp[$i] = $dp[$i - 1] + $dp[$i - 2];
    }
    
    return $dp[$n];
}

2. 0-1背包问题

function knapSack($W, $weights, $values, $n) {
    $dp = array_fill(0, $n + 1, array_fill(0, $W + 1, 0));
    
    for ($i = 1; $i <= $n; $i++) {
        for ($w = 1; $w <= $W; $w++) {
            if ($weights[$i - 1] <= $w) {
                $dp[$i][$w] = max(
                    $values[$i - 1] + $dp[$i - 1][$w - $weights[$i - 1]],
                    $dp[$i - 1][$w]
                );
            } else {
                $dp[$i][$w] = $dp[$i - 1][$w];
            }
        }
    }
    
    return $dp[$n][$W];
}

加密算法

1. MD5加密

function md5Hash($string) {
    return md5($string);
}

2. SHA256加密

function sha256Hash($string) {
    return hash('sha256', $string);
}

路径查找算法

1. Dijkstra最短路径算法

function dijkstra($graph, $start) {
    $distances = [];
    $visited = [];
    $vertices = array_keys($graph);
    
    foreach ($vertices as $vertex) {
        $distances[$vertex] = INF;
        $visited[$vertex] = false;
    }
    
    $distances[$start] = 0;
    
    for ($i = 0; $i < count($vertices) - 1; $i++) {
        $minVertex = minDistance($distances, $visited);
        $visited[$minVertex] = true;
        
        foreach ($graph[$minVertex] as $vertex => $weight) {
            if (!$visited[$vertex] && $distances[$minVertex] != INF && 
                $distances[$minVertex] + $weight < $distances[$vertex]) {
                $distances[$vertex] = $distances[$minVertex] + $weight;
            }
        }
    }
    
    return $distances;
}

function minDistance($distances, $visited) {
    $min = INF;
    $minVertex = null;
    
    foreach ($distances as $vertex => $distance) {
        if (!$visited[$vertex] && $distance <= $min) {
            $min = $distance;
            $minVertex = $vertex;
        }
    }
    
    return $minVertex;
}

树算法

1. 二叉树遍历(前序、中序、后序)

class TreeNode {
    public $value;
    public $left;
    public $right;
    
    public function __construct($value) {
        $this->value = $value;
        $this->left = null;
        $this->right = null;
    }
}

// 前序遍历
function preOrder($root) {
    if ($root != null) {
        echo $root->value . " ";
        preOrder($root->left);
        preOrder($root->right);
    }
}

// 中序遍历
function inOrder($root) {
    if ($root != null) {
        inOrder($root->left);
        echo $root->value . " ";
        inOrder($root->right);
    }
}

// 后序遍历
function postOrder($root) {
    if ($root != null) {
        postOrder($root->left);
        postOrder($root->right);
        echo $root->value . " ";
    }
}

实用算法

1. 生成随机字符串

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    
    return $randomString;
}

2. 验证邮箱格式

function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

PHP 高级算法与实用技巧

分治算法

1. 归并排序

function mergeSort($array) {
    if (count($array) <= 1) {
        return $array;
    }
    
    $mid = (int)(count($array) / 2);
    $left = array_slice($array, 0, $mid);
    $right = array_slice($array, $mid);
    
    return merge(mergeSort($left), mergeSort($right));
}

function merge($left, $right) {
    $result = [];
    while (count($left) > 0 && count($right) > 0) {
        if ($left[0] < $right[0]) {
            $result[] = array_shift($left);
        } else {
            $result[] = array_shift($right);
        }
    }
    
    return array_merge($result, $left, $right);
}

2. 快速选择算法(寻找第K小元素)

function quickSelect($array, $k) {
    if (count($array) <= 1) {
        return $array[0] ?? null;
    }
    
    $pivot = $array[0];
    $left = $right = [];
    
    for ($i = 1; $i < count($array); $i++) {
        if ($array[$i] < $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }
    }
    
    $leftCount = count($left);
    if ($k <= $leftCount) {
        return quickSelect($left, $k);
    } elseif ($k == $leftCount + 1) {
        return $pivot;
    } else {
        return quickSelect($right, $k - $leftCount - 1);
    }
}

贪心算法

1. 找零钱问题

function coinChange($coins, $amount) {
    rsort($coins); // 从大到小排序
    $result = [];
    
    foreach ($coins as $coin) {
        while ($amount >= $coin) {
            $amount -= $coin;
            $result[] = $coin;
        }
    }
    
    return $amount === 0 ? $result : false;
}

2. 活动选择问题

function activitySelection($activities) {
    // 按结束时间排序
    usort($activities, function($a, $b) {
        return $a[1] - $b[1];
    });
    
    $selected = [];
    $lastEnd = 0;
    
    foreach ($activities as $activity) {
        if ($activity[0] >= $lastEnd) {
            $selected[] = $activity;
            $lastEnd = $activity[1];
        }
    }
    
    return $selected;
}

回溯算法

1. 八皇后问题

class NQueens {
    private $solutions = [];
    private $size;
    
    public function solve($n) {
        $this->size = $n;
        $this->backtrack([], 0);
        return $this->solutions;
    }
    
    private function backtrack($queens, $row) {
        if ($row === $this->size) {
            $this->solutions[] = $queens;
            return;
        }
        
        for ($col = 0; $col < $this->size; $col++) {
            if ($this->isSafe($queens, $row, $col)) {
                $queens[$row] = $col;
                $this->backtrack($queens, $row + 1);
            }
        }
    }
    
    private function isSafe($queens, $row, $col) {
        for ($i = 0; $i < $row; $i++) {
            // 检查列冲突和对角线冲突
            if ($queens[$i] === $col || 
                abs($queens[$i] - $col) === abs($i - $row)) {
                return false;
            }
        }
        return true;
    }
}

2. 全排列生成

function permutations($array) {
    $result = [];
    $this->permute($array, 0, count($array) - 1, $result);
    return $result;
}

private function permute(&$array, $left, $right, &$result) {
    if ($left == $right) {
        $result[] = $array;
    } else {
        for ($i = $left; $i <= $right; $i++) {
            $this->swap($array, $left, $i);
            $this->permute($array, $left + 1, $right, $result);
            $this->swap($array, $left, $i);
        }
    }
}

private function swap(&$array, $i, $j) {
    $temp = $array[$i];
    $array[$i] = $array[$j];
    $array[$j] = $temp;
}

图算法进阶

1. Floyd-Warshall 最短路径算法

function floydWarshall($graph) {
    $dist = $graph;
    $n = count($dist);
    
    for ($k = 0; $k < $n; $k++) {
        for ($i = 0; $i < $n; $i++) {
            for ($j = 0; $j < $n; $j++) {
                if ($dist[$i][$k] + $dist[$k][$j] < $dist[$i][$j]) {
                    $dist[$i][$j] = $dist[$i][$k] + $dist[$k][$j];
                }
            }
        }
    }
    
    return $dist;
}

2. Kruskal 最小生成树算法

class Kruskal {
    private $parent = [];
    
    public function findMST($edges, $vertices) {
        usort($edges, function($a, $b) {
            return $a[2] - $b[2];
        });
        
        foreach ($vertices as $vertex) {
            $this->parent[$vertex] = $vertex;
        }
        
        $mst = [];
        foreach ($edges as $edge) {
            $root1 = $this->find($edge[0]);
            $root2 = $this->find($edge[1]);
            
            if ($root1 != $root2) {
                $mst[] = $edge;
                $this->parent[$root1] = $root2;
            }
        }
        
        return $mst;
    }
    
    private function find($vertex) {
        if ($this->parent[$vertex] != $vertex) {
            $this->parent[$vertex] = $this->find($this->parent[$vertex]);
        }
        return $this->parent[$vertex];
    }
}

实用数据处理算法

1. 大数据分块处理

function processLargeData($data, $chunkSize, $callback) {
    $total = count($data);
    $processed = 0;
    
    while ($processed < $total) {
        $chunk = array_slice($data, $processed, $chunkSize);
        $callback($chunk);
        $processed += count($chunk);
    }
}

2. 内存高效数组去重

function largeArrayUnique($array) {
    $temp = [];
    foreach ($array as $key => $value) {
        $hash = md5(serialize($value));
        if (!isset($temp[$hash])) {
            $temp[$hash] = $value;
        }
    }
    return array_values($temp);
}

性能优化技巧

1. 记忆化技术(Memoization)

function memoize($func) {
    $cache = [];
    return function() use ($func, &$cache) {
        $args = func_get_args();
        $key = md5(serialize($args));
        
        if (!isset($cache[$key])) {
            $cache[$key] = call_user_func_array($func, $args);
        }
        
        return $cache[$key];
    };
}

// 使用示例
$fibonacci = memoize(function($n) {
    return ($n <= 1) ? $n : $fibonacci($n - 1) + $fibonacci($n - 2);
});

2. 延迟加载大数据集

class LazyDataLoader implements Iterator {
    private $position = 0;
    private $data = [];
    private $loadCallback;
    private $chunkSize;
    
    public function __construct($loadCallback, $chunkSize = 1000) {
        $this->loadCallback = $loadCallback;
        $this->chunkSize = $chunkSize;
        $this->loadChunk();
    }
    
    private function loadChunk() {
        $this->data = call_user_func(
            $this->loadCallback, 
            $this->position, 
            $this->chunkSize
        );
        $this->position += $this->chunkSize;
    }
    
    public function current() {
        return current($this->data);
    }
    
    public function next() {
        next($this->data);
        if (key($this->data) === null) {
            $this->loadChunk();
        }
    }
    
    public function key() {
        return key($this->data);
    }
    
    public function valid() {
        return key($this->data) !== null;
    }
    
    public function rewind() {
        $this->position = 0;
        $this->loadChunk();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值