Home  >  Article  >  Backend Development  >  PHP二分法 查寻

PHP二分法 查寻

WBOY
WBOYOriginal
2016-06-13 13:11:36939browse

PHP二分法 查找
二分法 的思想是这样的 给我一个数组  我把数组的头和尾索引相加 除2 这样就得出中间的位置索引 拿我要找的数的值 和中间索引位置的值做比较
如果相等就返回这个中间位置的索引. 如果中间位置的值大于索要查找的值 将中间位置索引作为 尾索引 再和头索引相加 除2 得出中间索引 比较,
如果中间位置的值 小于要找的值 将中间位置索引作为 头索引 再和尾索引相加 除2得出中间索引 比较.如此循环知道找到为止.

<?php
        $arr = array(1,2,3,4,5,6,7,8,9);
        print_r(binarySearch($arr,9));
        function binarySearch($arr,$Num){
                $StartPos=0;
                $EndPos = count($arr)-1;
                $m = (int)(($EndPos+$StartPos)/2);
                while($arr[$m]!=$Num){
                        if($arr[$m] == $Num){
                                break;
                        }else if($arr[$m] < $Num){
                                $StartPos = (int)$m;
                                if($m+$EndPos>(2*$m)){
                                        $m= (int)(($m+$EndPos)/2)+1;
                                }
                        }else if($arr[$m] > $Num){
                                $EndPos = (int)$m;
                                 $m= (int)(($m+$StartPos)/2);
                        }
                }
                return $m;
        }
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn