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.
Copy codeThe 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 )));
}