PHP Data structure (1) binary search

Source: Internet
Author: User
: 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.

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.