Php binary search implementation example. Php binary search examples binary search commonly used methods include recursion and non-recursion. when looking for the value, you can use interpolation instead of the median method. Php binary search example:
Binary search is commonly written in recursion and non-recursion. when looking for the value, you can use interpolation instead of the median method.
When the data in an ordered array increases evenly, the algorithm complexity can be reduced from the lgN of the mean method to lglgN by interpolation.
The code is as follows:
/**
* Binary search recursive solution
* @ Param type $ subject
* @ Param type $ start
* @ Param type $ end
* @ Param type $ key
* @ Return boolean
*/
Function binarySearch_r ($ subject, $ start, $ end, $ key)
{
If ($ start >=$ end) return FALSE;
$ Mid = getMidKey ($ subject, $ start, $ end, $ key );
If ($ subject [$ mid] ==$ key) return $ mid;
If ($ key> $ subject [$ mid]) {
Return binarySearch ($ subject, $ mid, $ end, $ key );
}
If ($ key <= $ subject [$ mid]) {
Return binarySearch ($ subject, $ start, $ mid, $ key );
}
}
/**
* Non-recursive algorithms for binary search
* @ Param type $ subject
* @ Param type $ n
* @ Param type $ key
*/
Function binarySearch_nr ($ subject, $ n, $ key)
{
$ Low = 0;
$ High = $ n;
While ($ low <= $ high ){
$ Mid = getMidKey ($ subject, $ low, $ high, $ key );
If ($ subject [$ mid] ==$ key) return $ mid;
If ($ subject [$ mid] <$ key ){
$ Low = $ mid + 1;
}
If ($ subject [$ mid]> $ key ){
$ High = $ mid-1;
}
}
}
Function getMidKey ($ subject, $ low, $ high, $ key)
{
/**
* The method used to extract the value from Algorithm 1 ($ low + $ high)/2 is used to prevent overflow when the values of low and high are large ....
*/
// Return round ($ low + ($ high-$ low)/2 );
/**
* The improved interpolation algorithm calculates the mean value. when the value distribution is even, the complexity of the algorithm is reduced to lglgN.
* Median Algorithm 2
*/
Return round ($ key-$ subject [$ low])/($ subject [$ high]-$ subject [$ low]) * ($ high-$ low )));
}
Recursive and non-recursive methods are commonly used for finding the mean value. when looking for the mean value, you can use interpolation instead of the mean value method. When the data in the ordered array increases evenly ,...