查找
1.顺序查找
$arr = array(1,2,3,4,4);
//顺序查找
function search($value, &$arr)
{
$arr_search = array();
foreach ($arr as $k=>$v)
{
if($v==$value)
{
$arr_search[$k] = $v;
}
}
if(empty($arr_search))
{
return false;
}else{
return $arr_search;
}
}
var_dump(search(4,$arr));
//顺序查找
function search($value, &$arr)
{
$arr_search = array();
foreach ($arr as $k=>$v)
{
if($v==$value)
{
$arr_search[$k] = $v;
}
}
if(empty($arr_search))
{
return false;
}else{
return $arr_search;
}
}
var_dump(search(4,$arr));
2.二分法查找
/**
* 二分查找,前提是该数组必须是个有序的才行,如果不是必须先排序
*/
$arr = array(1,2,3,4,5,6);
function binarySearch($value, &$arr, $leftIndex, $rightIndex)
{
if($rightIndex<$leftIndex)
{
echo '找不到该数';
exit();
}
//首先找到中间数,并不一定非得是正中间
$middleIndex = round(($rightIndex+$leftIndex)/2);
//如果大于则,向后找
if($value>$arr[$middleIndex]){
binarySearch($value, $arr, $middleIndex+1, $rightIndex);
}elseif($value<$arr[$middleIndex]){
binarySearch($value, $arr, $leftIndex, $middleIndex-1);
}else{
echo '找到了,下标是:'.$middleIndex;
}
}
print_r(binarySearch(6, $arr, 0, count($arr)-1));
* 二分查找,前提是该数组必须是个有序的才行,如果不是必须先排序
*/
$arr = array(1,2,3,4,5,6);
function binarySearch($value, &$arr, $leftIndex, $rightIndex)
{
if($rightIndex<$leftIndex)
{
echo '找不到该数';
exit();
}
//首先找到中间数,并不一定非得是正中间
$middleIndex = round(($rightIndex+$leftIndex)/2);
//如果大于则,向后找
if($value>$arr[$middleIndex]){
binarySearch($value, $arr, $middleIndex+1, $rightIndex);
}elseif($value<$arr[$middleIndex]){
binarySearch($value, $arr, $leftIndex, $middleIndex-1);
}else{
echo '找到了,下标是:'.$middleIndex;
}
}
print_r(binarySearch(6, $arr, 0, count($arr)-1));