算法-随手写的二分查找
1 <?php 2 function search($arr, $num) { 3 $len = count($arr); 4 5 $start = 0; 6 $end = $len - 1; 7 $mid = floor(($start + $end) / 2); 8 9 while($start <= $end) { 10 echo $start, ':', $mid, ':', $end, '<br />'; //输出查找流程 11 12 if ($num == $arr[$mid]) { 13 return $mid; 14 }elseif ($num > $arr[$mid]) { 15 $start = $mid + 1; 16 } elseif ($num < $arr[$mid]) { 17 $end = $mid - 1; 18 } 19 $mid = floor(($start + $end) / 2); 20 } 21 return -1; 22 } 23 24 $search_arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 25 echo '4的索引值为:', search($search_arr, 4);