Home > php教程 > php手册 > php 二分算法查找

php 二分算法查找

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 19:58:15
Original
997 people have browsed it

? /** * 二分算法查找 * @param array $array 要查找的数组 * @param int $min_key 数组的最小下标 * @param int $max_key 数组的最大下标 * @param mixed $value 要查找的 * @return boolean */ function bin_search($array,$min_key,$max_key,$value){ if(


/**    

* 二分算法查找

* @param array $array 要查找的数组

* @param int $min_key 数组的最小下标

* @param int $max_key 数组的最大下标

* @param mixed $value 要查找的值

* @return boolean

*/

function bin_search($array,$min_key,$max_key,$value){

  if($min_key

      $key = intval(($min_key+$max_key)/2);

      if($array[$key] == $value){

          return true;

      }elseif($value

          return bin_search($array,$min_key,$key-1,$value);

      }else{

          return bin_search($array,$key+1,$max_key,$value);

      }

  }else{

      return false;

  }

}

//现在我们来测试一下这个函数

$array = array(1,22,23,45,58,10,12,2,4,6);

$value = 45;

$min_key = min(array_keys($array));

$max_key = max(array_keys($array));

if(bin_search($array,$min_key,$max_key,$value)){

  echo "Search Success!";

}else{

  echo "Search Faliure!";

}
?>

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template