1、顺序查找
1 function line_search($array,$tar) 2 { 3 if(!is_array($array) || count($array) < 1) return false; 4 for($i=0;$i<count($array);$i++){ 5 if($array[$i] == $tar){ 6 return $i; 7 } 8 } 9 return false; 10 } 11 12 line_search($arr,34);
2、二分法查找
1 // 非递归 2 function binary_search($array,$tar) 3 { 4 if(!is_array($array) || count($array) < 1) return false; 5 // 数组必须排序 6 sort($array); 7 $high = count($array) - 1; 8 $low = 0; 9 while($low <= $high){ 10 $middle = intval(($high + $low) / 2); 11 if($array[$middle] > $tar){ 12 $high = $middle - 1; 13 }elseif($array[$middle] < $tar){ 14 $low = $middle + 1; 15 }else{ 16 return $middle; 17 } 18 } 19 return false; 20 } 21 22 binary_search($arr,165.4);
1 // 递归 2 function binary_search($array,$tar,$high=0,$low=0) 3 { 4 if(!is_array($array) || count($array) < 1) return false; 5 sort($array); 6 if($low <= $high){ 7 $middle = intval(($high + $low) / 2); 8 if($array[$middle] > $tar){ 9 $high = $middle - 1; 10 echo $high."</br>"; 11 return binary_search($array,$tar,$high,$low); 12 }elseif($array[$middle] < $tar){ 13 $low = $middle + 1; 14 return binary_search($array,$tar,$high,$low); 15 }else{ 16 return $middle; 17 } 18 } 19 return false; 20 } 21 22 binary_search($arr,125,count($arr),0);
原文地址:https://www.cnblogs.com/wawjandcsws/p/11081513.html
时间: 2024-10-26 21:22:01