Php binary lookup whether an array contains a certain element _ PHP Tutorial

Source: Internet
Author: User
The php binary method is used to check whether an array contains a certain element. The binary search array contains a certain element, which is compatible with positive and negative order. the code is implemented as follows :? Php $ searchValue (int) $ _ GET [key]; functionsearch (array $ array, $ value) {$ max returns an array containing a certain element in a forward/backward order, 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.

The pipeline code is as follows :? Php $ searchValue = (int) $ _ GET ['key']; function search (array $ array, $ value) {$ max...

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.