Parse the php binary method to find whether an array contains a certain element
Source: Internet
Author: User
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;
}
}
}
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.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.