binarySearch.php
<?php class Algorithm { static function binarySearch( $arr, $num ) { $trials = 1; // 試行回数 $low = 0; // 最小範囲 $high = count( $arr ) - 1; // 最大範囲 while( $low <= $high ) { $pivot = ($low + $high) / 2; $pivot = (int)$pivot; if($arr[$pivot] == $num) { return array( $num, $trials ); } if($num > $arr{$pivot}) { $low = $pivot + 1; } if($num < $arr{$pivot}) { $high = $pivot -1; } ++$trials; } return null; } } // ------------------------------------------------------------ $arr = array( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ); $num = 8; // ------------------------------------------------------------ $anser = Algorithm::binarySearch( $arr, $num ); var_dump($anser); echo "<hr/>"; echo "ナンバー:{$anser[0]} <br/>"; echo "試行回数:{$anser{1}} <br/>";
表示結果
array(2) { [0]=> int(8) [1]=> int(4) } ナンバー:8 試行回数:4