PHP学习笔记【13】--查找
2012-11-26 00:25
393 查看
<?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
相关文章推荐
- PHP学习笔记【13】--查找
- PHP学习笔记(13)班级和学生管理---班级
- PHP学习笔记第【13】天(2014.11.16)——oop编程
- PHP学习笔记13淘宝接口开发一例(tmall.items.discount.search),PHP
- PHP学习笔记13----PHP+MYSQL分页原理
- php学习笔记(13):PHP+MYSQL简单分页
- PHP学习笔记13——SQL支持(mysql库与PDO)
- lua学习笔记13:查找并替换文件中关键字
- php 学习笔记--数组篇(13)
- PHP学习笔记【13】_正则表达式
- php学习笔记(二)——数据删除,修改,查找
- 【小白笔记】PHP学习之路 (13) --数组(3)
- PHP学习笔记 13 - Datetime
- 【小白笔记】PHP学习之路 (10) --字符串(2)
- Linux学习笔记--7.vim查找替换
- PHP学习笔记(15)PDO数据库操作+AJAX无刷新技术删除用户
- PHP学习笔记:PERL兼容正则表达式
- PHP学习笔记 (1)-环境配置与代码调试
- php学习笔记------[php中面向对象三大特性之一[封装性]的应用]
- PHP学习笔记之字符串编码的转换和判断