Binary lookup Algorithm (JAVA)

Source: Internet
Author: User

1. Two points lookup is also called binary lookup, it is a more efficient way to find.

2. Two-point lookup requirements: (1) The sequential storage structure (2) must be used. Must be sorted by keyword size

3. Principle: The array is divided into three parts, followed by the median (the so-called median is the middle of the array of values) before, median, median, the value to be looked up and the median value of the array, if less than the median value in front of the median value is found, if the value is greater than the median value is returned after the median Then there is a recursive procedure, in which the first half or the second part continues to be decomposed into three parts.

The basic idea of its finding: first, compare the given value K with the key of the middle position element in the table, and if it is equal, return the storage location of the element; if not, the element to be searched can only be in the first half or the second half of the intermediate data. Then continue with the same search in the narrowed range. So repeat until you find it.

4. Implementation: Binary lookup implementation by recursion and loop two ways

5. Code:

1  PackageOther ;2 3  Public classBinarySearch {4     /*5 * Loop Implementation binary Lookup algorithm arr already ordered array x number of lookups required-1 Unable to find data6      */7      Public Static intBinarySearch (int[] arr,intx) {8         intLow = 0; 9         intHigh = Arr.length-1; Ten          while(Low <=High ) {    One             intMiddle = (low + high)/2;  A             if(x = =Arr[middle]) {    -                 returnMiddle;  -}Else if(X <Arr[middle]) {    theHigh = Middle-1;  -}Else {    -Low = middle + 1;  -             }   +         }   -         return-1;  +     } A     //recursive implementation of binary search at      Public Static intBinarySearch (int[] DataSet,intDataintBeginindex,intEndIndex) {     -            intMidindex = (beginindex+endindex)/2;  -            if(Data <dataset[beginindex]| | data>dataset[endindex]| | Beginindex>EndIndex) {   -                return-1;  -            }   -            if(Data <Dataset[midindex]) {     in                returnBinarySearch (dataset,data,beginindex,midindex-1);  -}Else if(data>Dataset[midindex]) {     to                returnBinarySearch (dataset,data,midindex+1, EndIndex);  +}Else {     -                returnMidindex;  the            }     *        }    $ Panax Notoginseng      Public Static voidMain (string[] args) { -         int[] arr = {6, 12, 33, 87, 90, 97, 108, 561 }; theSystem.out.println ("Loop lookup:" + (BinarySearch (arr, 87) + 1)); //Loop Lookup: 4--This 4 represents the position of the array
System.out.println ("Loop lookup:" + BinarySearch (arr.));  Loop Lookup: 3--This 3 represents the index value of the array
 System.out.println ("Recursive lookup" +binarysearch (arr,87,3,arr.length-1
41
42

Because the binary lookup needs to conveniently locate the lookup area, the storage structure that is suitable for binary lookups must have a randomly stored feature.

Therefore, the lookup method is only suitable for the sequential storage structure of linear tables, is not suitable for chained storage structures, and requires elements to be ordered in an orderly manner by keyword .

decision tree (and Binary tree):

  The binary lookup process can be represented, called a decision tree, (binary tree). Each circular node in the tree represents a record, and the value in the node is represented as a key value for the record: the bottom-most leaf node in the tree is square, which indicates that the lookup was unsuccessful. From the decision tree, it can be seen that the lookup is successful when the lookup length is the number of nodes on the path from the root node to the destination node, while the lookup is unsuccessful when the lookup length is the number of nodes from the root node to the parent node of the corresponding failed node; If there are n elements in an ordered sequence, the corresponding decision tree has n circular non-leaf nodes and n+1 square leaf nodes.

  

, the depth of a tree consisting of n circular nodes (representing an ordered sequence of n elements) is equal to the depth (height) of the full binary tree of n nodes, both ⌊log2n⌋+1 or ⌈log2 (n+1) ⌉

The time complexity of binary lookup is O (log2n), which is more efficient than sequential lookup.

From the above analysis, it is found that a binary lookup to a given value or a lookup failure is no more than the height of the tree. Finding success and not succeeding, in the worst case, you need to compare ⌊log2n⌋+1 times.

Precautions:

Binary lookup is a binary sort tree, where the value of each root node is greater than the value of all nodes of the left subtree, less than the value of all nodes of the right subtree.


Advantages and disadvantages of two-point search
Although binary lookups are efficient, you want to sort the tables by keyword. The sort itself is a time-consuming operation. It also takes an O (NLGN) time to use an efficient sorting method.
Binary lookup applies only to sequential storage structures. To maintain the order of the table, it is necessary to move a large number of nodes to insert and delete in the sequential structure. As a result, binary search is especially useful for linear tables that are rarely modified and often need to be found once created.
For those linear tables that find little and often need to be changed, a chain list can be used as a storage structure for sequential lookups. Binary lookups cannot be implemented on a linked list.

Specific can be Baidu under the judgment tree

Binary lookup Algorithm (JAVA)

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.