This article gives a detailed analysis of whether an array contains a certain element in the binary search of php. if you need a friend, refer to the binary search to see if the array contains a certain element. This article is compatible with positive and negative orders, code implementation:
The code is as follows:
$ SearchValue = (int) $ _ GET ['key'];
Function search (array $ array, $ value)
{
$ Max = count ($ array)-1;
$ Min = 0;
$ IsAscSort = $ array [$ min] <$ array [$ max];
While (TRUE ){
$ Sum = $ min + $ max;
$ MidKey = (int) ($ sum % 2 = 1? Ceil ($ sum/2): $ sum/2 );
If ($ max <$ min ){
Return-1;
} Else if ($ value = $ array [$ midKey]) {
Return 1;
} Else if ($ value> $ array [$ midKey]) {
$ IsAscSort? $ Min = $ midKey + 1: $ max = $ midKey-1;
} Else if ($ value <$ array [$ midKey]) {
$ IsAscSort? $ Max = $ midKey-1: $ min = $ midKey + 1;
}
}
}
$ Array = array (
'4', '5', '7', '8', '9', '10', '11', '12'
);
// Forward
Echo search ($ array, $ searchValue );
// Reverse order
Rsort ($ array );
Echo search ($ array, $ searchValue );
I have searched for this before and have read the Baidu encyclopedia example (Java implementation). There are some other Code written by other technical experts, which is problematic and cannot be implemented at all, these people are misleading when they are not tested. you can search for them and share them with others if you have nothing to worry about yesterday.
This does not take into account the unordered key array, mainly the method. if you need it, you can expand it on your own.