//冒泡法排序
//随便给出一个乱序数组
$arr = array(0,2,10,9,19,23,89,112,321,234);
//统计数组
$num = count($arr);
//冒泡倒序排列
for($i=0;$i<$num-1;$i++){
for($m=0;$m<$num-1;$m++){
if($arr[$m]<$arr[$m+1]){
$temp = $arr[$m];
$arr[$m] = $arr[$m+1];
$arr[$m+1] = $temp;
}
// echo $arr[$m].' ';
}
}
//输出排序后的结果
var_dump($arr);
//冒泡顺序排列
for($x=0;$x<$num-1;$x++){
for($y=0;$y<$num-1;$y++){
if($arr[$y]>$arr[$y+1]){
$temp = $arr[$y];
$arr[$y] = $arr[$y+1];
$arr[$y+1] = $temp;
}
}
}
//输出排序后的结果
var_dump($arr);
//二分法查找
function dichotomy($array,$k,$low=0,$high=0){
if(count($array)!= 0 && $high == 0){
$high = count($array);
}
if($low <= $high){
$mid = intval(($low+$high)/2);
if( $array[$mid] == $k ){
return $mid;
}elseif( $k<$array[$mid]){
return dichotomy( $array,$k,$low=0,$mid-1);
}else{
return dichotomy( $array,$k,$mid+1,$high);
}
}else{
return false;
}
}
//输出查找结果
echo dichotomy($arr,23);
|