本文实例讲述了php实现的二分查找算法。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<?php
$arr = array (4,58,11,34,88,45,32,54,63,78);
function binary( $arr , $bnum )
{
if ( is_array ( $arr ) && count ( $arr ) > 0)
{
sort( $arr );
$start = 0;
$end = count ( $arr )-1;
$mid = -1;
while ( $start <= $end )
{
$mid = floor ( ( $start + $end )/2 );
if ( $arr [ $mid ] == $bnum )
{
return $arr [ $mid ];
} else if ( $arr [ $mid ] < $bnum )
{
$start = $mid +1;
} else if ( $arr [ $mid ] > $bnum )
{
$end = $mid - 1;
}
}
return -1;
}
}
$mm = binary( $arr ,32);
print_r( $mm ); //输出32
?>
|
希望本文所述对大家PHP程序设计有所帮助。