算法-随手写的二分查找

 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);

 

posted on 2013-08-09 13:31  John_ABC  阅读(288)  评论(0编辑  收藏  举报

导航