上次写个二分查找,错误百出,唉,还真如编程珠玑里面说的,写二分查找的人 90%都不会一次成功。深深的鄙视一下自己,贴一下二分的代码,以及二分查找的变种代码
- //二分查找
- function binary _search($search, $data_arr, $lower, $upper)
- {
- if($lower > $upper)
- {
- return false;
- }
- $mid = intval( ($lower + $upper) / 2 );
- if($search == $data_arr[$mid])
- {
- return $mid;
- }elseif($search < $data_arr[$mid])
- {
- $upper = $mid - 1;
- }else
- {
- $lower = $mid + 1;
- }
- return search($search, $data_arr, $lower, $upper);
- }
- /*
- * 二分查找变种,查找$search第一次出现的位置 ,对于传值,$lower=-1 $upper=count($data_arr)
- *
- * array(0,2,3,7,8,8,8,9,10)
- * binary_search_begin(8, ....)
- * 返回值4
- */
- function binary_search_begin($search, $data_arr, $lower, $upper)
- {
- if( ($lower + 1) == $upper )
- {
- return ($data_arr[$upper] == $search)? $upper : -1;
- }
- $mid = intval( ($lower + $upper) / 2 );
- if( $data_arr[$mid] < $search )
- {
- $lower = $mid;
- }else
- {
- $upper = $mid;
- }
- return binary_search_begin($search, $data_arr, $lower, $upper);
- }
- /*
- * 二分查找变种,查找$search最后一次出现的位置 ,对于传值,$lower=-1 $upper=count($data_arr)
- * array(0,2,3,7,8,8,8,9,10)
- * binary_search_begin(8, ....)
- * 返回值6
- */
- function binary_search_end($search, $data_arr, $lower, $upper)
- {
- if( ($lower + 1) == $upper )
- {
- return ($data_arr[$lower] == $search)? $lower : -1;
- }
- $mid = intval( ($lower + $upper) / 2 );
- if( $data_arr[$mid] > $search )
- {
- $upper = $mid;
- }else
- {
- $lower = $mid;
- }
- return binary_search_end($search, $data_arr, $lower, $upper);
- }
其迭代方法的实现为:
- //二分查找
- function binary_search($search, $data_arr, $lower, $upper)
- {
- while($lower <= $upper)
- {
- $mid = intval( ($lower + $upper) / 2 );
- if($data_arr[$mid] > $search)
- {
- $upper = $mid - 1;
- }elseif($data_arr[$mid] < $search)
- {
- $lower = $mid + 1;
- }else
- {
- return $mid;
- }
- }
- return false;
- }
- /*
- * 二分查找变种,查找$search第一次出现的位置,对于传值,$lower=-1 $upper=count($data_arr)
- * array(0,2,3,7,8,8,8,9,10)
- * binary_search_begin(8, ....)
- * 返回值4
- */
- function binary_search_begin($search, $data_arr, $lower, $upper)
- {
- while($lower + 1 != $upper)
- {
- $mid = intval( ($lower + $upper) / 2 );
- if($data_arr[$mid] < $search)
- {
- $lower = $mid;
- }else
- {
- $upper = $mid;
- }
- $p = $upper;
- if($data_arr[$p] != $search)
- {
- $p = false;
- }
- }
- return $p;
- }
- /*
- * 二分查找变种,查找$search最后一次出现的位置,对于传值,$lower=-1 $upper=count($data_arr)
- * array(0,2,3,7,8,8,8,9,10)
- * binary_search_begin(8, ....)
- * 返回值6
- */
- function binary_search_end($search, $data_arr, $lower, $upper)
- {
- while($lower + 1 != $upper)
- {
- $mid = intval( ($lower + $upper) / 2 );
- if($data_arr[$mid] > $search)
- {
- $upper = $mid;
- }else
- {
- $lower = $mid;
- }
- $p = $lower;
- if($data_arr[$p] != $search)
- {
- $p = false;
- }
- }
- return $p;
- }