您的位置:首页 > 编程语言 > PHP开发

PHP学习笔记【13】--查找

2013-04-01 16:13 344 查看
 
 

<?php 
    //查找, 在一个数组中找到你想要的数据 
     
    //从数组 34,234,7,454,23 查找 7 
    //顺序查找 
    $a=array(-1,0,7,23,45,6767,7878); 
    function search($arr,$findVal){ 
        for($v=0;$v<count($arr);$v++){ 
            if($findVal==$arr[$v]){ 
                echo "找到了,索引为:".$v; 
            } 
        } 
    } 
     
    //search($a,7); 
     
    //二分查找:(数组是有序的) 
    //首先找到数组中间这个数,然后跟要查找的数进行比较,如果比要查找的数字大,则在上边查找, 
    //如果小的话就在下面查找,知道查找到该数即可停止 
    function binarySearch($arr,$findVal,$minIndex,$maxIndex){ 
        if($maxIndex<=$minIndex){ 
            if($findVal==$arr[$maxIndex]){ 
                echo "找到该数字,索引为:".$maxIndex; 
            }else{ 
                echo "找不到该数字"; 
            } 
            return ; 
             
        } 
        $middle=round(($minIndex+$maxIndex)/2); 
            if($findVal<$arr[$middle]){ 
                binarySearch($arr,$findVal,$minIndex,$middle-1); 
            }else if($findVal>$arr[$middle]){ 
                binarySearch($arr,$findVal,$middle+1,$maxIndex); 
            }else{ 
                echo "找到了索引为".$middle; 
                return ; 
            } 
         
    } 
    binarySearch($a,0,0,6); 
?> 

 
本文出自 “Kenan_ITBlog” 博客,请务必保留此出处http://soukenan.blog.51cto.com/5130995/1070619
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: