Binary search algorithm

Source: Internet
Author: User

Binary search also known as binary lookup, the advantages are less than the number of comparisons, Find Fast, the average performance is good, the disadvantage is that the unknown origin table is ordered table, and insert delete difficult. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent. First, suppose that the elements in the table are arranged in ascending order, comparing the keywords in the middle position of the table with the lookup keywords, and if they are equal, the lookup succeeds; otherwise, the table is divided into the front and the last two sub-tables with the intermediate positional records, and if the middle position record keyword is greater than the Find keyword, the previous child Otherwise, find the latter child table further. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful at this time.

The basic idea of binary search is to divide n elements into roughly equal two parts, take A[N/2] and X to compare, if X=A[N/2], then find X, the algorithm aborts, if X<A[N/2], as long as the left half of the array a continues to search X, if X>A[N/2], Search for x in the right half of the array A.

Example of Java development

 PackageTwog;/*** Binary algorithm: Advantages--less than the number of comparisons, Find Fast, average performance is good. Disadvantage--requires that the unknown origin table be an ordered table, and insert Delete is difficult. * Suitable for infrequently changing and frequently ordered lists * * The basic idea of binary search is to divide n elements into roughly equal two parts, go to A[N/2] and X to compare, if X=A[N/2], the algorithm terminates, * if X<A[N/2], then the left half of X Partial search X, if X>A[N/2], to search X in the right half of X *@authorDELL **/ Public classBinarySearch {Private intRcount = 0; Private intLCount = 0; /*** Number of times to get recursion*/     Public intGetrcount () {returnRcount; }    /*** Get cycle times **/     Public intGetlcount () {returnLCount; }    /*** Executes a recursive binary algorithm that returns the position of the first occurrence of the value * Sorteddate already sorted array * Start position * END END position * Findvalue need to find the value * RE Turn position in array, starting from 0, cannot find return-1 * **/     Public intSearchrecursive (int[] Sorteddata,intStartintEndintfindvalue) {Rcount++;//recursion Count        if(start<=end) {              //Middle Position            intMiddle= (start+end) >>1;//equivalent (start+end)/2//Medium Value            intMiddlevalue=Sorteddata[middle]; if(findvalue==middlevalue) {                  //equals the median to return directly                returnMiddle; }              Else if(findvalue<middlevalue) {                  //is less than the median value before the median value is found                returnSearchrecursive (sorteddata,start,middle-1, findvalue); }              Else              {                  //greater than median is found after median value                returnSearchrecursive (sorteddata,middle+1, End,findvalue); }          }          Else          {              //I can't find them .            return-1; }      }            /*** Loop binary lookup, returns the position of the first occurrence of this value *@paramsorteddata Sorted Array *@paramFindvalue need to find the value *@returnThe position of the value in the array, starting at 0. No return-1 found*/       Public intSearchloop (int[] Sorteddata,intfindvalue) {          intStart=0; intEnd=sorteddata.length-1;  while(start<=end) {LCount++;//Number of Cycles//Middle Position            intMiddle= (start+end) >>1;//equivalent (start+end)/2//Medium Value            intMiddlevalue=Sorteddata[middle]; if(findvalue==middlevalue) {                  //equals the median to return directly                returnMiddle; }              Else if(findvalue<middlevalue) {                  //is less than the median value before the median value is foundEnd=middle-1; }              Else              {                  //greater than median is found after median valueStart=middle+1; }          }          //I can't find them .        return-1; }       }
 PackageTwog; Public classBinarysearchtest { Public voidTestsearch () {BinarySearch BS=NewBinarySearch (); int[] sorteddata={1,2,3,4,5,6,6,7,8,8,9,10}; intFindvalue=9; intLength=sorteddata.length; /*** Recursive two-part algorithm*/        intPos=bs.searchrecursive (sorteddata, 0, Length-1, findvalue); System.out.println ("Recursice:" +findvalue+ "found in Pos" +pos+ "; Count:" +Bs.getrcount ()); /*** Circular binary search*/        intPos2=Bs.searchloop (Sorteddata, findvalue); System.out.println ("Loop:" +findvalue+ "found in Pos" +pos+ "; Count:" +Bs.getlcount ()); }       Public Static voidMain (string[] args) {binarysearchtest T=Newbinarysearchtest ();    T.testsearch (); }}

Binary search 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.