循序搜索法
就是一個一個去比較,找到時返回;
二元搜索法
二元搜索算法是在排好序的數組中找到特定的元素.
首先, 比較數組中間的元素,如果相同,則返回此元素的指針,表示找到了. 如果不相同, 此函數就會繼續搜索其中大小相符的一半,然后繼續下去. 如果剩下的數組長度為0,
則表示找不到,那么函數就會結束.
實現代碼:
package com.zc.manythread;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author 偶my耶
* 循環查找
* 二元查找
*/
public class LinearSearch {
//循序搜索
public static int LinearSearch(int[] list,int item)
{
for(int i = 0 ; i < list.length;i++)
{
if(list[i]==item)
return i;//找到傳回的位置
}
return -1;//找不到時
}
//二元搜尋,傳入的數先排序好,由小至大
public static int BinarySearch(int[] list,int item)
{
//初始左右二邊
int left = 0 ;
int right = list.length;
//左邊的索引位置小于右邊的索引的位置
while(left<=right)
{
int mid = (left + right)/2;
if(list[mid]==item)
return mid;
else
{
//所查詢值比中間值小,故值會在中間的左邊數列
if(list[mid]>item)
{
right = mid -1;
}else
{
left = mid +1;
}
}
}
return -1;//找不到時
}
/**
* 產生隨機數組
* @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 {
// 如果產生的數相同繼續循環
num = rand.nextInt(100);
} while (bool[num]);
bool[num] = true;
data[i]=num;
}
return data;
}
public static void main(String args[])
{
//輸入要查找的數
Scanner in = new Scanner(System.in);
//循序搜尋案列
int[] list = createDate(10);
System.out.println("原始數列:");
for(int i = 0 ; i <list.length ; i ++)
{
System.out.print(list[i]+" ");
}
System.out.println("/r/n請輸入要查詢的數:");
int searchkey = in.nextInt();
int ans = LinearSearch(list,searchkey);
if(ans>-1)
{
System.out.println("找到數,位置在:"+(ans+1)+"位");
}
else
System.out.println("找不著");
//二元搜尋案列
int[] list2 = {2,4,6,8,10,12,13,14,15,16};
System.out.println("原始數據:");
for(int i = 0 ; i<list2.length ; i ++)
{
System.out.print(list2[i]+" ");
}
System.out.println("/r/n請輸入要查詢的數:");
int searchkey2 = in.nextInt();
int ans2 = BinarySearch(list2,searchkey2);
if(ans2>-1)
{
System.out.println("找到數,位置在:"+ans2+"位");
}
else
System.out.println("找不著!");
}
}
運行結果

以上就是本文的全部內容了,希望大家能夠喜歡。