I wrote a binary search function by myself, which is implemented in php. I believe many people have encountered such problems during the interview. Okay, too much nonsense. let's get started! /*** Binary search * @ paramarray $ array the minimum subscript of the array * @ paramint $ min_key * @ paramint $ max_key
I wrote a binary search function by myself, which is implemented in php. I believe many people have encountered such problems during the interview. Okay, too much nonsense. let's get started!
/*** Binary algorithm search * @ param array $ array the array to be searched * @ param int $ minimum subscript of the min_key array * @ param int $ maximum subscript of the max_key array * @ param mixed $ value the value to be searched * @ return boolean */function bin_search ($ array, $ min_key, $ max_key, $ value) {if ($ min_key <= $ max_key) {$ key = intval ($ min_key + $ max_key)/2 ); if ($ array [$ key] ==$ value) {return true;} elseif ($ value <$ array [$ key]) {return bin_search ($ array, $ min_key, $ key-1, $ value);} else {return bin _ Search ($ array, $ key + 1, $ max_key, $ value) ;}} else {return false ;}} // Now let's test this function $ array = array (, 58); $ value = 45; $ min_key = min (array_keys ($ array )); $ max_key = max (array_keys ($ array); if (bin_search ($ array, $ min_key, $ max_key, $ value) {echo "Search Success! ";} Else {echo" Search Faliure! ";}
In this way, the binary search function is implemented, isn't it easy?
Two knowledge points are involved:
The first is the concept of the binary algorithm:
1. prerequisite for binary search: nodes in the table are ordered by keywords and stored in sequence (one-dimensional array.
2. bipartite thinking: moderate and comparison
(2.1) calculate the mid position in the middle of the ordered table
(2.2) if r [mid]. key = k, the search is successful. if r [mid]. key> k, continue to perform binary search in the left subtable; if r [mid]. key <k, binary search continues in the right word table
Then there is recursion. everyone is familiar with this and I will not talk about it here.