Java implements three common search algorithms (sequential search, binary lookup, binary sort tree lookup)

Source: Internet
Author: User

 Public classSearch { Public classbitreenode{intM_nvalue;        Bitreenode M_pleft;            Bitreenode M_pright; }    //sequential lookup, which returns the value subscript, is not found to return -1.     Public intSequencesearch (int[] A,intb) {        if(a==NULL)            return-1;  for(inti=0;i<a.length;i++){            if(a[i]==b)returni; }        return-1; }    //binary lookup, binary lookup, required to find the array is ordered. Suitable for static lookups only.      Public intBinarySearch (int[] A,intb) {        if(a==NULL)            return-1; intLow=0; intHigh=a.length-1;  while(low<=High ) {            intMiddle= (Low+high)/2; if(a[middle]==b)returnMiddle; if(a[middle]<b) Low=middle+1; Else High=middle-1; }        return-1; }    //recursive algorithm for binary lookup     Public intBinarySearch1 (int[] A,intBintLowintHigh ) {        if(a==NULL|| Low>High )return-1; intMiddle= (Low+high)/2; if(a[middle]==b)returnMiddle; if(a[middle]<b)returnBinarySearch1 (a,b,middle+1, high); Else            returnBinarySearch1 (a,b,low,middle-1); }    //Two fork sorting tree, binary search tree, two searches tree, is a tree with the following characteristics, the tree's left is smaller than it, the tree's right side is larger than it.      PublicBitreenode Binarybisearch (Bitreenode phead,intb) {        if(phead==NULL)            return NULL; if(phead.m_nvalue==b)returnPhead; if(phead.m_pleft!=NULL)            returnBinarybisearch (PHEAD.M_PLEFT,B); if(phead.m_pright!=NULL)            returnBinarybisearch (PHEAD.M_PRIGHT,B); return NULL; }     Public Static voidMain (string[] args) {int[] a={1,2,3,5,7,8,10}; Search Search=NewSearch (); intI=search. BinarySearch (a,1); intK=search. BinarySearch1 (A, 3,0,a.length-1); intJ=search. Sequencesearch (A, 3); System.out.println (i+ "" +j+ "" +k); }}

Java implements three common search algorithms (sequential search, binary lookup, binary sort tree lookup)

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.