二分 end 向下取整 必须 blog else 从大到小 function pre
- <?php
- //设置请求头
- header("content-type:text/html;charset=utf-8");
- /*
- 二分差查找:
- 源:数组
- 条件:必须是有序的数据,要么从小到大,要么从大到小
- */
- $arr = array(1,2,3,4,5);
- /*
- @$arr 源数组
- @$arr_start_index 开始下标
- @$arr_end_index 结束下标
- @$number 要查找的数
- */
- function search(&$arr, $arr_start_index, $arr_end_index, $number){
- //防止下标重合
- if($arr_start_index > $arr_end_index){
- echo ‘不存在改值‘;
- exit;
- }
- $arr_center_index = round( ($arr_start_index + $arr_end_index)/2 ); //向下取整
- if($arr[$arr_center_index] > $number){
- search($arr, $arr_center_index, $arr_end_index-1, $number);
- }
- else if($arr[$arr_center_index] < $number){
- search($arr, $arr_start_index+1, $arr_center_index, $number);
- }
- else if($arr[$arr_center_index] == $number){
- echo ‘存在给值,该值在数组中的下标为:‘ . $arr_center_index;
- exit;
- }
- echo ‘不存在改值‘;
- exit;
- }
- search($arr, 0, 4,5);
- ?>
数组查找之二分查找-PHP
来源: http://www.bubuko.com/infodetail-2319314.html