Java Implementation Binary lookup (dichotomy)

Source: Internet
Author: User

Implementing binary Lookups with Java

Basic idea: While recursive loop, constantly judge A[middle] is equal to data, if it is equal to jump out of the loop, return the index value, if not equal, until the two are equal, where the Count counter records the number of lookups, Considered an element does not exist when count is more than 20 times (here to be optimized)

 Packagetest;/** Binary search (binary find) * tgmoving **/ Public classHalfsearch { Public Static intHalfsearch (intA[],intdata) {                intLength =a.length; intStart = 0; intEnd = Length-1; intMiddle = (start + end)/2; intCount = 1;//used for counting, binary lookups more than 20 times still not found as this element does not exist                 while(data!=A[middle]) {             if(Start > End | | count > 20){                return-1; }Else{                if(Data <A[middle]) {End=Middle; Middle= (start + end)/2; System.out.println ("+" + (count+1) + "search data < A[middle]:" + "index:" +middle); }Else if(Data >A[middle]) {Start= middle + 1; Middle= (start + end)/2; System.out.println ("+" + (count+1) + "search data > A[middle]:" + "index:" +middle); }} Count++; } Count= 0; returnMiddle; }             Public Static voidMain (String[]args) {intA[] = {1,2,3,4,5,6,7}; intindex = Halfsearch (A, 7); System.out.println ("Isexist:" +index); }}

Running results show:

Java Implementation Binary lookup (dichotomy)

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.