Java version of the binary algorithm implementation

Source: Internet
Author: User
Algorithm class ERFENFA


{


int[] iarray={1,5,9,14,27,39,41,50,62,222,345,612,981,1207,8721}; Looking for
in this sequence of numbers

int iseek=345; Search 345 of Locations


int icount=0; Number of comparisons





public int Xunhuan ()


//Common cycle method, need to compare at least once, such as looking for 1, the maximum need to compare 15 times, such as 8721


{


for (int i=0;i<iarray.length;i++)


{


icount++;


if (Iseek==iarray[i])


break;


}


return icount;


}





public int Erfen ()


//Two-way search


{


int iindex=0; The equivalent of a pointer to something


int istart=0; //


int iend=iarray.length-1;


while (true)


{


icount++;


Iindex = (istart+iend)/2;


if (iarray[iindex]<iseek)


{


IStart = Iindex;


}


else if (Iarray[iindex]>iseek)


{


iend = Iindex;


}


Else


{


break;


}


}


return icount;


}





public static void Main (string[] args)


{


Erfenfa eff=new Erfenfa ();


Erfenfa eff1=new Erfenfa ();


System.out.println ("Common cycle lookup, the number of times to compare:" +eff.xunhuan ());


System.out.println ("binary search, the number of times to compare:" +eff1.erfen ());


}


}














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.