java實現查找算法(一):線性查找,折半查找

[b] 一 線性查找[/b]

public class LSearch
{
public static int[] Data = { 12, 76, 29, 22, 15, 62, 29, 58, 35, 67, 58,
33, 28, 89, 90, 28, 64, 48, 20, 77 }; // 輸入數據數組

public static int Counter = 1; // 查找次數計數變量

public static void main(String args[])
{

int KeyValue = 22;
// 調用線性查找
if (Linear_Search((int) KeyValue))
{
// 輸出查找次數
System.out.println("");
System.out.println("Search Time = " + (int) Counter);
}
else
{
// 輸出沒有找到數據
System.out.println("");
System.out.println("No Found!!");
}
}

// ---------------------------------------------------
// 順序查找
// ---------------------------------------------------
public static boolean Linear_Search(int Key)
{
int i; // 數據索引計數變量

for (i = 0; i < 20; i++)
{
// 輸出數據
System.out.print("[" + (int) Data[i] + "]");
// 查找到數據時
if ((int) Key == (int) Data[i])
return true; // 傳回true
Counter++; // 計數器遞增
}
return false; // 傳回false
}
}

運行結果:
[12][76][29][22]
Search Time = 4

[b]
二 折半查找[/b]

public class BSearch
{
public static int Max = 20;
public static int[] Data = { 12, 16, 19, 22, 25, 32, 39, 48, 55, 57, 58,
63, 68, 69, 70, 78, 84, 88, 90, 97 }; // 數據數組
public static int Counter = 1; // 計數器

public static void main(String args[])
{
int KeyValue = 22;
// 調用折半查找
if (BinarySearch((int) KeyValue))
{
// 輸出查找次數
System.out.println("");
System.out.println("Search Time = " + (int) Counter);
}
else
{
// 輸出沒有找到數據
System.out.println("");
System.out.println("No Found!!");
}
}

// ---------------------------------------------------
// 折半查找法
// ---------------------------------------------------
public static boolean BinarySearch(int KeyValue)
{
int Left; // 左邊界變量
int Right; // 右邊界變量
int Middle; // 中位數變量

Left = 0;
Right = Max - 1;

while (Left <= Right)
{
Middle = (Left + Right) / 2;
if (KeyValue < Data[Middle]) // 欲查找值較小
Right = Middle - 1; // 查找前半段
// 欲查找值較大
else if (KeyValue > Data[Middle])
Left = Middle + 1; // 查找後半段
// 查找到數據
else if (KeyValue == Data[Middle])
{
System.out.println("Data[" + Middle + "] = " + Data[Middle]);
return true;
}
Counter++;
}
return false;
}
}

運行結果:
Data[3] = 22
Search Time = 5


原文網址:http://blog.csdn.net/myjava_024/archive/2008/11/18/3331247.aspx
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章