$test_array = array (- 98, - 10, 0, 5, 6, 23, 98, 235 );
$index1 = bin_sch ( $test_array, 0, 8, - 98 );
echo 'find index:' . $index1;
//二分查找
function bin_sch($array, $low, $high, $k) {
if ($low <= $high && count ( $array ) >= $high) {
$mid = intval ( ($low + $high) / 2 );
if ($array [$mid] == $k) {
return $mid;
} elseif ($k < $array [$mid]) {
return bin_sch ( $array, $low, $mid - 1, $k );
} else {
return bin_sch ( $array, $mid + 1, $high, $k );
}
}
return - 1;
}
//顺序查找(数组里查找某个元素)
function seq_sch($array, $n, $k){
$array[$n] = $k; //防止溢出
for($i=0; $i<$n; $i++){
if($array[$i]==$k){
break;
}
}
if ($i<$n){
return $i;
}else{
return -1;
}
}