This article mainly introduces the binary search algorithm in PHP, combined with examples to summarize and analyze the principle of two-point search algorithm and specific implementation skills, the need for friends can refer to the next
Binary search in the advanced point of development may be used, of course, in large companies to find jobs will have the interview question is this, the following we look at a binary method to find the implementation method in PHP, the specific details are as follows.
The dichotomy method (Dichotomie) is the method of splitting, and a closed interval of R is set [A, b], and successive dichotomy is the creation of the following interval sequence ([an,bn]): A0=a,b0=b, and for any natural number n,[an+1,bn+1] or 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);//dichotomy to find 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:
The <?php//search function, where $array is an array, $k the value to find, $low the minimum key value for the lookup range, $high the maximum key value for the lookup range function search ($array, $k, $low =0, $high =0) { if (count ($array)!=0 and $high = = 0)//Determine if the call is the first time { $high = count ($array); } if ($low <= $high)//If there are remaining array elements { $mid = intval (($low + $high)/2);//Take the middle value of $low and $high if ($array [$mid] = = $K)//return {return $mid if found ; } ElseIf ($k < $array [$mid])//If not found, continue to find { 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); Test the search function echo search ($array, 8); Call the search function and output the lookup results?>
Summary: The above is the entire content of this article, I hope to be able to help you learn.