JAVA Binary Search method

Source: Internet
Author: User

The binary lookup method is to find a number Val in an array from small to large, first with the number of Val and median to be searched, if it is larger than the median value, then to the right of the median value, if it is smaller than the median value, then find it on the left of the median. Keep going. Know to find Val. If not found, the output has no relevant data in the sequence.

 Public classTest2 { Public Static voidMain (string[] args) {int[] Arr ={1, 5, 9, 56, 78, 80, 85, 99};//Note that the array needs to be sorted from small to large. Binaryfind (0, Arr.length-1, 85, arr); }         /**         * @author          * @paramLeft array index *@paramRight array and subscript *@paramarr Array Reference *@paramVal to find the number * @ function: implementation in a heap number to find if there is a Val number, call this binary lookup method premise is that the sequence arr is ordered*/         Public Static voidBinaryfind (intLeftintRightintValint[] arr) {                        if(left <= right)//binary search is actually traversing the array, make sure that the left subscript is not greater than the right subscript            {                               intPivot =arr[(left+right)/2];//Find the middle number                                if(Val < pivot)//If the number you are looking for is smaller than the median, look to the left of the median value{binaryfind ( left) (left+ right)/2-1, Val, arr); }Else if(val > Pivot)//If the number you are looking for is larger than the median, look for the median value to the right{Binaryfind ( left+ right)/2 +1, right, Val, arr); }Else if(val = =pivot) {System.out.println ("The number of" +val+ "is found in the array sequence, and its subscript is:" + ((left+right)/2 ) ); }            }            Else{System.out.println ("Unfortunately the number you are looking for is not in the array sequence."); }        }    }

JAVA Binary Search method

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.