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
相关文章推荐
- PHP学习笔记【13】--查找
- php学习笔记(13):PHP+MYSQL简单分页
- PHP学习笔记(13)班级和学生管理---班级
- PHP学习笔记第【13】天(2014.11.16)——oop编程
- php 学习笔记--数组篇(13)
- PHP学习笔记13淘宝接口开发一例(tmall.items.discount.search),PHP
- PHP学习笔记13----PHP+MYSQL分页原理
- php学习笔记(二)——数据删除,修改,查找
- PHP学习笔记13——SQL支持(mysql库与PDO)
- lua学习笔记13:查找并替换文件中关键字
- PHP学习笔记【13】_正则表达式
- PHP学习笔记 13 - Datetime
- 【小白笔记】PHP学习之路 (13) --数组(3)
- PHP学习笔记【4】--apache服务器配置--配置虚拟目录和配置虚拟主机
- PHP 学习笔记 (6)
- 韩顺平PHP学习视频笔记整理004html基本操作
- PHP and Web Services 学习笔记
- [原创][技术]PHP学习笔记(2)--基础2/3
- Scala学习笔记13【trait之多重继承、AOP实战】
- php学习笔记-03