欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php 实现一个排序算法找出数组中最大/最小的数

程序员文章站 2022-05-12 10:34:20
...
<?php
/**
 * Created by phpStorm.
 * User: BinWei
 * Date: 2019/6/1
 * Time: 19:29
 */


/**
 * @description 获取数组中最大/最小值
 * @param $list
 * @param string $type
 * @return mixed|null
 * @author BinWei
 */
function getMaxOrMin($list, $type = 'max')
{
    $target = null;
    switch ($type) {
        case 'max':
            $target = $list[0];
            unset($list[0]);
            foreach ($list as $key => $value) {
                if ($value > $target) {
                    $target = $value;
                }
            }
            break;
        case 'min':
            $target = $list[0];
            unset($list[0]);
            foreach ($list as $key => $value) {
                if ($value < $target) {
                    $target = $value;
                }
            }
            break;
    }
    return $target;
}


$list = [0, 1, 2, 3, 4, 5, 10, -1];
var_dump(getMaxOrMin($list, 'min'));