This article mainly introduces the binary search algorithm in PHP. It summarizes and analyzes the principles and specific implementation techniques of the binary search algorithm in the form of examples. Friends in need can refer to the following
Biometric search in advanced points It may be used in development. Of course, when looking for a job in a large company, there will be interview questions like this. Let's take a look at an article about how to implement binary search in PHP. The specific details are as follows.
Dichotomy (dichotomie) is a method of dividing into two. Let [a, b] be the closed interval of R. The successive dichotomy method is to create the following interval sequence ([an, bn]): a0= a, b0=b, and for any natural number n, [an 1, bn 1] is either equal to [an, cn], or equal to [cn, bn], where cn represents the midpoint of [an, bn].
Example 1:
header('Content-Type: text/html; charset=utf-8;'); $arr = array(2,33,22,1,323,321,28,36,90,123); sort($arr); //二分法查找 echo $index = binarySearch($arr,321); function binarySearch($arr,$key){ $len = count($arr); $mid = -1; $start = 0; $end = $len-1; while($start<=$end){ $mid = (int)(($start+$end)/2); echo $mid."\n"; if($arr[$mid] == $key){ return $mid; }else if($arr[$mid] < $key){ $start = $mid+1; }else if($arr[$mid] > $key){ $end = $mid-1; } } }
Example 2:
<?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函数并输出查找结果 ?>
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
phpImplement database operation Model class
phpImplement URL encryption and decryption
PHP foreach implements traversal of multi-dimensional arrays
The above is the detailed content of Detailed explanation of binary search algorithm examples in PHP. For more information, please follow other related articles on the PHP Chinese website!