Binary Lookup algorithm

Source: Internet
Author: User

Overview

?? The binary search method mainly solves the problem of "finding the specified number in a pile number". To apply a binary lookup method, this "pile number" must have a feature:

    • stored in the array
    • Orderly arrangement

So if you are using a linked list, you cannot apply a binary lookup method on it. (Ozone in the interview is asked what data structures can be used on the binary lookup method: arrays? Linked list? It does not matter whether the same element exists in the array if the order is ascending or descending. In general, however, we hope and assume that the arrays are ascending and that the elements in the array are different.

theory

See:
Http://www.cnblogs.com/ider/archive/2012/04/01/binary_search.html
Http://taop.marchtea.com/04.01.html

Recursive implementation binary lookup (PHP)
 function re_binary_search($arr,$target,$height,$low =0){    if($height<$low||$arr[$low] >$target||$arr[$height] <$target){return-1; }$mid= Intval (($low+$height)/2);if($arr[$mid] >$target){//First half segment        returnRe_binary_search ($arr,$target,$mid-1,$low); }if($arr[$mid] <$target){//second half segment        returnRe_binary_search ($arr,$target,$height,$mid+1); }return $mid;}
non-recursive implementation binary lookup (PHP)
 function binary_search($arr,$target){    $length= Count ($arr);if($length<=0||$arr[0] >$target||$arr[$length-1] <$target){return-1; }$low=0;$height=$length-1; while($low<=$height){$mid= (int) (($low+$height)/2);if($arr[$mid] >$target){$height=$mid-1; }Else if($arr[$mid] <$target){$low=$mid+1; }Else{return $mid; }    }return-1;}
called
var_dump(re_binary_search($item,‘8‘,count($item)-1));var_dump($item[re_binary_search($item,‘8‘,count($item)-1)]);var_dump(binary_search($item,‘8‘));var_dump($item[binary_search($item,‘8‘)]);
Results

Binary Lookup algorithm

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.