: This article mainly introduces the PHP Data structure (1) binary search. if you are interested in the PHP Tutorial, refer to it. The basic idea of binary search is to compare the size of the value in the middle of an ordered array with the value in the search. when the value in the search is greater than the value in the middle of the array, that is, all values before the median of the ordered array are smaller than the value of the query. Therefore, all values before the median of the ordered array can be excluded, then, from the median of the array to the value at the end of the array, continue to find the required value. The code implementation is as follows:
// Binary search
Function bin_search ($ array, $ search ){
$ Low = 0;
$ Height = count ($ array)-1; // Get the array length
While ($ low <= $ height ){
$ Mid = floor ($ low + $ height)/2); // gets the intermediate number, which is forcibly converted to the floor type to prevent errors
If ($ array [$ mid] ==$ search ){
Return $ mid + 1; // return the sequence number that has been found.
} Else if ($ array [$ mid] <$ search ){
// When the median value is less than the queried value, the left value of $ mid is less than $ search, and $ mid is assigned to $ low.
$ Low = $ mid + 1;
} Else if ($ array [$ mid]> $ search ){
// If the median value is greater than the queried value, all values on the right of $ mid are greater than $ search. in this case, $ mid is assigned to $ height.
$ Height = $ mid-1;
}
Return "search failed"; // search failed. this value does not exist in the array.
}
}
$ Arr = array );
Echo bin_search ($ arr, 33 );
Echo bin_search ($ arr, 66 );
?>
The above introduces the PHP Data structure (1) binary search, including the content, hope to be helpful to friends who are interested in the PHP Tutorial.