Examples of binary search algorithms in php and Analysis of Binary Search instances
This article describes how to implement the Binary Search Algorithm in php. We will share this with you for your reference. The details are as follows:
Binary lookup may be used in the development of advanced points. Of course, this is the case when you are looking for a job in a large company. Let's take a look at the implementation method of binary lookup in php, the details are as follows.
Dichotomie (dichotomie) is a split-in method. If [a, B] is a closed interval of R, the successive bipartite method is used to create the following interval sequence ([an, bn]): a0 =, b0 = B, and for any natural number n, [an + 1, bn + 1] or equal to [an, cn], or [cn, bn], cn indicates the midpoint of [an, bn.
Example 1:
Header ('content-Type: text/html; charset = UTF-8; '); $ arr = array (323,321, 90,123,); sort ($ arr ); // search for echo $ index = binarySearch ($ arr, 321) by using the binary method; 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:
<? In the php // search function, $ array is the array, $ k is the value to be searched, and $ low is the minimum key value in the search range, $ high: function search ($ array, $ k, $ low = 0, $ high = 0) {if (count ($ array )! = 0 and $ high = 0) // determines whether it is the first call {$ high = count ($ array);} if ($ low <= $ high) // if there are still remaining array elements {$ mid = intval ($ low + $ high)/2 ); // obtain the intermediate values of $ low and $ high if ($ array [$ mid] ==$ k) // if yes, {return $ mid;} is returned ;} elseif ($ k <$ array [$ mid]) // if not found, continue to search for {return search ($ array, $ k, $ low, $ mid-1);} else {return search ($ array, $ k, $ mid + 1, $ high) ;}} return-1 ;} $ array = array (,); // test the search function echo search ($ Rray, 8); // call the search function and output the search result?>