• 技术文章 >php教程 >PHP源码

    php二分法

    PHP中文网PHP中文网2016-05-25 17:13:07原创519

    [PHP]代码

    $array = array(1,2,3,4,11,12,124,1245);
    function found($array,$low,$hight,$k)
    {
    	$index = intval(($low+$hight) / 2);
    	if($k == $array[$index])
    	{
    		return $index;
    	}elseif($k < $array[$index])
    	{
    		return found($array,$low,$index-1,$k);
    	}else{
    		return found($array,$index+1,$hight,$k);
    	}
    
    }
    echo found($array,0,$count,1245);
    
    /**改进型不使用递归*/
    function find($arr,$v)
    {
    	$start = 0;
    	$end   = count($arr) - 1;
    
    	while($start <= $end)
    	{
    		$index = intval(($start + $end) / 2);
    		
    		if($v < $arr[$index])
    		{
    			$end = $index - 1;
    		}
    		elseif($v > $arr[$index])
    		{
    			$start = $index + 1;
    		}
    		else
    		{
    			return $index;
    		}
    	}
    	return -1;
    }
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:php
    上一篇:PHP导出Excel的类库,支持附带图片 下一篇:php生成密保卡

    相关文章推荐

    • PHP禁止图片文件的被盗链函数• 使用simple_html_dom抓取oschina的新闻资讯• 解决json_encode 函数中文被编码成 null的办法• php学习笔记之面向对象编程• php中常用的函数集合

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网