算法学习--二分法
运用语言PHP
<?php //二分法 function dichotomy(array $arrays,$frist,$last,$num){ $model=floor(($last+$frist)/2); if($arrays[$model]==$num){ echo "It is inset"; }else{ if($arrays[$model]>$num){ $last=$model-1; }else{ $frist=$model+1; } if($frist>$last){ //判断条件 echo "It is not inset"; exit; } dichotomy($arrays, $frist, $last, $num); } } //冒泡排序---> 顺序 function bubble_sort($array){ $total=count($array); for($i=0;$i<=($total-2);$i++){ //执行n-1次 for($j=0;$j<=($total-2-$i);$j++){ //比较n-i-1次 if($array[$j]>=$array[$j+1]){ $m=$array[$j]; $array[$j]=$array[$j+1]; $array[$j+1]=$m; } } } return $array; } $array=array(12,15,45,84,51,69,23); $num=15; $arrays=bubble_sort($array); var_dump($arrays); $frist=0; $last=count($arrays)-1; dichotomy($arrays, $frist, $last,$num); ?>