php 数组二分法查找函数代码

yipeiwu_com6年前PHP代码库
复制代码 代码如下:

<?php
//search函数 其中$array为数组,$k为要找的值,$low为查找范围的最小键值,$high为查找范围的最大键值
function search($array, $k, $low=0, $high=0)
{
if(count($array)!=0 and $high == 0) //判断是否为第一次调用
{
$high = count($array);
}
if($low <= $high) //如果还存在剩余的数组元素
{
$mid = intval(($low+$high)/2); //取$low和$high的中间值
if ($array[$mid] == $k) //如果找到则返回
{
return $mid;
}
elseif ($k < $array[$mid]) //如果没有找到,则继续查找
{
return search($array, $k, $low, $mid-1);
}
else
{
return search($array, $k, $mid+1, $high);
}
}
return -1;
}
$array = array(4,5,7,8,9,10); //测试search函数
echo search($array, 8); //调用search函数并输出查找结果
?>

相关文章

PHP遍历目录函数opendir()、readdir()、closedir()、rewinddir()总结

在进行PHP编程时,需要对服务器某个目录下面的文件进行浏览,通常成为遍历目录。取得一个目录下的文件和子目录,就需要用到opendir()函数、readdir()函数、closedir()...

PHP 类型转换函数intval

PHP代码 $id = intval($_GET['id']); intval (PHP 4, PHP 5) intval — Get the integer value of a va...

PHP 如何利用phpexcel导入数据库

废话不多说,直接上代码吧复制代码 代码如下:<?php error_reporting(E_ALL); //开启错误 set_time_limit(0); //脚本不超时 date...

jQuery+php简单实现全选删除的方法

本文实例讲述了jQuery+php简单实现全选删除的方法。分享给大家供大家参考,具体如下: <input type="checkbox" id="ckb_selectAll"...

php checkdate、getdate等日期时间函数操作详解

checkdate($month,$date,$year)   如果应用的值构成一个有效日期,则该函数返回为真。例如,对于错误日期2005年2月31日,此函数返回为假。   在日期用于计...