Home > Backend Development > PHP Tutorial > PHP binary search example sharing

PHP binary search example sharing

小云云
Release: 2023-03-21 09:46:01
Original
1348 people have browsed it

This article mainly shares binary search PHP examples with you. This article mainly shares it with you in the form of code. I hope it can help you.

Easy to use

/**
*  二分查找
**/
function binarySearch(Array $arr, $target) {  
   $low = 0;  
   $high = count($arr) - 1;  
     
   while($low <= $high) {  
       $mid = floor(($low + $high) / 2);  
       #找到元素。  
       if($arr[$mid] == $target) return $mid;  
       #中元素比目标大,查找左部。  
       if($arr[$mid] > $target) $high = $mid - 1;  
       #重元素比目标小,查找右部。  
       if($arr[$mid] < $target) $low = $mid + 1;  
   }  
  
   #查找失败  
   return false;  
}  
  
$arr = array(1, 3, 5, 7, 9, 11);  
$inx = binarySearch($arr, 7);  
echo $inx."<hr/>"; // 索引位置。
Copy after login

Related recommendations:

php binary search algorithm example sharing

Example analysis PHP Implemented binary search algorithm

php method to implement binary search algorithm

The above is the detailed content of PHP binary search example sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template