Sequential Search method
is to compare one to another and return when found;
Binary Search method
A binary search algorithm finds a specific element in a sorted array.
First, the elements in the middle of the array are compared, and if the same, a pointer to this element is returned, indicating that it is found. If not, the function will continue to search for half the size that matches, and then continue. If the remaining array length is 0,
is not found, then the function ends.
Implementation code:
PackageCom.zc.manythread;ImportJava.util.Random;ImportJava.util.Scanner;/** * * @authorMy yes * Loop Lookup * $ two lookup*/ Public classLinearsearch {//Sequential Search Public Static intLinearsearch (int[] list,intItem) { for(inti = 0; I < list.length;i++) { if(list[i]==Item)returnI//find the returned location } return-1;//when you can't find them } //two USD Search, incoming number first sorted well, from small to large Public Static intBinarySearch (int[] list,intItem) { //initial left and right two sides intleft = 0 ; intright =list.length; //the index position on the left is less than the position of the right index while(left<=Right ) { intMid = (left + right)/2; if(list[mid]==Item)returnmid; Else { //the query value is smaller than the median value, so the value is in the middle left column if(list[mid]>Item) { Right= Mid-1; }Else{ Left= Mid +1; } } } return-1;//when you can't find them } /*** Generate random array *@paramCount *@return */ Private Static int[] CreateDate (intcount) { int[] Data=New int[Count]; Random Rand=NewRandom (); Boolean[] bool =New Boolean[100]; intnum = 0; for(inti = 0; I < count; i++) { Do { //if the resulting number is the same, continue the loopnum = rand.nextint (100); } while(Bool[num]); Bool[num]=true; Data[i]=num; } returndata; } Public Static voidMain (String args[]) {//Enter the number you want to findScanner in =NewScanner (system.in); //Sequential search Case List int[] list = CreateDate (10); System.out.println ("Primitive Series:"); for(inti = 0; I <list.length; i + +) {System.out.print (List[i]+" "); } System.out.println ("\ r \ n Please enter the number to query:"); intSearchkey =In.nextint (); intAns =Linearsearch (List,searchkey); if(ans>-1) {System.out.println ("Find the number, position in:" + (ans+1) + "bit"); } ElseSystem.out.println ("I can't find it."); //$ Two Search case List int[] List2 = {2,4,6,8,10,12,13,14,15,16};System.out.println ("Raw Data:"); for(inti = 0; I<list2.length; i + +) {System.out.print (List2[i]+" "); } System.out.println ("\ r \ n Please enter the number to query:"); intSearchkey2 =In.nextint (); intAns2 =BinarySearch (List2,searchkey2); if(ans2>-1) {System.out.println ("Find the number, position in:" +ans2+ "bit"); } ElseSystem.out.println ("I can't find it!"); }}
Run results
Sequential and two-dollar search algorithm-java