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)