Php binary algorithm search

Source: Internet
Author: User
? * ** Binary algorithm search * @ paramarray $ array the minimum subscript of the array * @ paramint $ min_key array * @ paramint $ max_key array * @ parammixed $ value to search * @ returnboolean * functionbin_search ($ array, $ min_key, $ max_key, $ value) {if (

? /*** 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 * @ return boolean */function bin_search ($ array, $ min_key, $ max_key, $ value) {if (

/**

* 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 );

$ 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! ";

}
?>

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.