<?php
//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); |
|