To start learning some algorithms recently ... Some algorithms will make you sigh true to the clever. I think some algorithms have been invented and need to be a mathematician. Such as quick sort, simply sigh how he thought of ... No other people's intelligence can only read more than remember haha ~
Today write a simple algorithm, dichotomy.
<?PHPfunctionBsearch ($v,$arr){ $low= 0; $high=Count($arr)-1;//use subscript, note minus 1 while($low<=$high){//Note the equals sign $i=intval(($high+$low)/2); if($arr[$i] >$v){ $high=$i-1; } Else if($arr[$i] <$v){ $low=$i+1; } Else { return $i; } } return-1;//returned when not found-1}$arr=Array( 1, 3, 5, 7, 9, 13);EchoBsearch (13,$arr);//5Echo' ;EchoBsearch (14,$arr);//-1
Seemingly simple algorithm, or self-write down good haha ~
Note that when using the while, be sure to guard against infinite loops, pay attention to the termination of the cycle of judgment. For example $low<= $high, this equals number must have.
Two-part method PHP