Sequential Search method
is to compare one to another, to return when found;
Two-Element search method
The binary search algorithm is to find a specific element in a sorted array.
First, the elements in the middle of the array are compared, and if the same, the pointer to this element is returned, indicating that it was found. If not, this function will continue to search for half of the size that matches it, and then go on. If the remaining array length is 0,
is not found, the function ends.
Implementation code:
Copy Code code as follows:
Package com.zc.manythread;
Import Java.util.Random;
Import Java.util.Scanner;
/**
*
* @author Me Yes
* Loop Lookup
* Two Yuan Search
*/
public class Linearsearch {
Sequential search
public static int Linearsearch (int[] list,int Item)
{
for (int i = 0; i < list.length;i++)
{
if (List[i]==item)
Return i;//Find the returned location
}
return-1;//can't find the time
}
Binary search, the number of incoming first sorted well, from small to large
public static int BinarySearch (int[] list,int Item)
{
Initial left and right two sides
int left = 0;
int right = List.length;
The index position on the left is less than the index on the right
while (Left<=right)
{
int mid = (left + right)/2;
if (List[mid]==item)
return mid;
Else
{
The query value is smaller than the median value, so the value will be in the middle of the left sequence
if (List[mid]>item)
{
right = Mid-1;
}else
{
left = Mid +1;
}
}
}
return-1;//can't find the time
}
/**
* Generate random array
* @param count
* @return
*/
private static int[] CreateDate (int count) {
Int[] Data=new Int[count];
Random rand = new Random ();
boolean[] bool = new BOOLEAN[100];
int num = 0;
for (int i = 0; i < count; i++) {
do {
If the resulting number is the same as continuing the loop
num = rand.nextint (100);
while (Bool[num]);
Bool[num] = true;
Data[i]=num;
}
return data;
}
public static void Main (String args[])
{
Enter the number you want to find
Scanner in = new Scanner (system.in);
Sequential Search Case List
int[] List = CreateDate (10);
System.out.println ("Original series:");
for (int i = 0; I <list.length i + +)
{
System.out.print (list[i]+ "");
}
System.out.println ("\ r \ n Please enter the number to query:");
int searchkey = In.nextint ();
int ans = linearsearch (List,searchkey);
if (ans>-1)
{
System.out.println ("Find number, Position in:" + (ans+1) + "bit");
}
Else
System.out.println ("not Found");
Binary Search Case List
Int[] List2 = {2,4,6,8,10,12,13,14,15,16};
System.out.println ("Original data:");
for (int i = 0; I<list2.length i + +)
{
System.out.print (list2[i]+ "");
}
System.out.println ("\ r \ n Please enter the number to query:");
int searchkey2 = In.nextint ();
int ans2 = BinarySearch (List2,searchkey2);
if (ans2>-1)
{
System.out.println ("Find number, position in:" +ans2+ ");
}
Else
System.out.println ("Can't find it!");
}
}
Run results
The above is the entire content of this article, I hope you can enjoy.