Home  >  Article  >  Backend Development  >  Detailed explanation of binary search algorithm examples in PHP

Detailed explanation of binary search algorithm examples in PHP

墨辰丷
墨辰丷Original
2018-06-01 11:00:551598browse

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:

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!

Statement:
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