• PHP查找数组中最大值与最小值


    <?php
         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
         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

     

  • 相关阅读:
    H.Playing games
    P4721 【模板】分治 FFT
    hdu5730 分治fft
    hdu6394Tree lct
    bzoj2763: [JLOI2011]飞行路线 最短路
    bzoj2154: Crash的数字表格 莫比乌斯反演
    bzoj3211: 花神游历各国 线段树
    溢流
    css控制继承
    “<textarea>”内的文字对齐
  • 原文地址:https://www.cnblogs.com/zemliu/p/2641043.html
Copyright © 2020-2023  润新知