PHP查找数组中最大值与最小值的二个例子

发布时间:2019-08-20编辑:脚本学堂
如何在php中查找数组中的最大值与最小值呢?本文分享二例php代码,教给大家在php数组中查找最大值、最小值的方法,感兴趣的朋友可以参考下。

本节内容:
查找php数组的最大值与最小值

例子:
 

复制代码 代码示例:
<?php
/**
* 在php数组中,查找最大值与最小值
* by www.jb200.com
*/
     function maxMin(Array $arr) {
         $cmpTime = 0;
         $count = count($arr);
         $big = $small = $arr[0];
         for($i = 1; $i < $count; $i++) {
             $cmpTime++;
             if($big > $arr[$i]) {
                 $cmpTime++;
                 if($small > $arr[$i]) {
                     $small = $arr[$i];
                 }
             } else {
                 $big = $arr[$i];
             }
         }
        
         echo "ArrLeng: " . $count . "<br>";
         echo "CmpTime: " . $cmpTime . "<br>";
         echo "Big: " . $big . "<br>";
         echo "Small: " . $small . "<br>";
     }
    
     $arr = array(4, 6, 8, 1, 5, 4, 3, 9, 11, 3, 22, 100, 55, 0, 4, -1, 31, 210, -10);
     maxMin($arr);
 ?>
 

输出结果:
ArrLeng: 19
CmpTime: 29
Big: 210
Small: -10
说明:以上代码在查找时,比较是n次,而最坏时会2n次。

接下来分享一个稳定的1.5n次比较的方法,代码:
 

复制代码 代码示例:

<?php
/**
* 在php数组中,查找最大值与最小值
* by www.jb200.com
*/
     function maxMin(Array $arr) {
         $cmpTime = 0;
         $count = count($arr);
         $biggest = $smallest = $arr[$count - 1];
         #每次取出两个元素,比较两个元素的大小再与最大值和最小值比较
         for($i = 0; $i < $count - 1; $i += 2) {
             $cmpTime++;
             if($arr[$i] > $arr[$i + 1]) {
                $bigger = $arr[$i];
                $smaller = $arr[$i + 1];
             } else {
                $bigger = $arr[$i + 1];
                $smaller = $arr[$i];  
             }
             $cmpTime++;   
             if($bigger > $biggest) {
                 $biggest = $bigger;
             }
             $cmpTime++;
             if($smaller < $smallest) {
                $smallest = $smaller;
             }
         }

         echo "ArrLeng: " . $count . "<br>";
         echo "CmpTime: " . $cmpTime . "<br>";
         echo "Big: " . $biggest . "<br>";
         echo "Small: " . $smallest . "<br>";
     }
    
     $arr = array(4, 6, 8, 1, 5, 4, 3, 9, 11, 3, 22, 100, 55, 0, 4, -1, 31, 210, -10);
     maxMin($arr);
 ?>
 

输出结果:
ArrLeng: 19
CmpTime: 27
Big: 210
Small: -10