$arr[$i]) { $cmpTime++; if($small > $arr[$i]) { $small = $arr[$i]; } } else { $big = $arr[$i]; } } echo "ArrLeng: " . $count . ""; echo "CmpTime: " . $cmpTime . ""; echo "Big: " . $big . ""; echo "Small: " . $small . ""; } $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: 29Big: 210Small: -10
这个方法是一个不稳定的查找,找的时候比较是n次,而最坏的时候比较是2n次,下面来看一个稳定的1.5n次比较的方法
$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 . ""; echo "CmpTime: " . $cmpTime . ""; echo "Big: " . $biggest . ""; echo "Small: " . $smallest . ""; } $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: 27Big: 210Small: -10