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

 

 

 
 
  1. <?php 
  2.     //查找, 在一个数组中找到你想要的数据 
  3.      
  4.     //从数组 34,234,7,454,23 查找 7 
  5.     //顺序查找 
  6.     $a=array(-1,0,7,23,45,6767,7878); 
  7.     function search($arr,$findVal){ 
  8.         for($v=0;$v<count($arr);$v++){ 
  9.             if($findVal==$arr[$v]){ 
  10.                 echo "找到了,索引为:".$v
  11.             } 
  12.         } 
  13.     } 
  14.      
  15.     //search($a,7); 
  16.      
  17.     //二分查找:(数组是有序的) 
  18.     //首先找到数组中间这个数,然后跟要查找的数进行比较,如果比要查找的数字大,则在上边查找, 
  19.     //如果小的话就在下面查找,知道查找到该数即可停止 
  20.     function binarySearch($arr,$findVal,$minIndex,$maxIndex){ 
  21.         if($maxIndex<=$minIndex){ 
  22.             if($findVal==$arr[$maxIndex]){ 
  23.                 echo "找到该数字,索引为:".$maxIndex
  24.             }else
  25.                 echo "找不到该数字"
  26.             } 
  27.             return ; 
  28.              
  29.         } 
  30.         $middle=round(($minIndex+$maxIndex)/2); 
  31.             if($findVal<$arr[$middle]){ 
  32.                 binarySearch($arr,$findVal,$minIndex,$middle-1); 
  33.             }else if($findVal>$arr[$middle]){ 
  34.                 binarySearch($arr,$findVal,$middle+1,$maxIndex); 
  35.             }else
  36.                 echo "找到了索引为".$middle
  37.                 return ; 
  38.             } 
  39.          
  40.     } 
  41.     binarySearch($a,0,0,6); 
  42. ?> 

 

本文出自 “Kenan_ITBlog” 博客,请务必保留此出处http://soukenan.blog.51cto.com/5130995/1070619

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值