java實現查找算法(三):二叉查找樹算法

[b]二叉查找樹算法[/b]
形成樹型結構,在進行查找

public class BTreeSearch
{
public static int Max = 10;
public static int[] Data = { 15, 2, 13, 6, 17, 25, 37, 7, 3, 18 }; // 數據數組
public static int Counter = 1;

public static void main(String args[])
{
int i; // 循環計數變量
BNTreeArray BNTree = new BNTreeArray(); // 聲明二叉樹數組

BNTree.TreeData[0] = Data[0];

for (i = 1; i < Max; i++)
BNTree.Create(Data[i]); // 建立二叉查找樹

int KeyValue = 25;
// 調用二叉查找法
if (BNTree.BinarySearch(KeyValue) > 0)
// 輸出查找次數
System.out
.println("Search Time = " + BNTree.BinarySearch(KeyValue));
else
// 輸出沒有找到數據
System.out.println("No Found!!");
}
}

class BNTreeArray
{
public static int MaxSize = 20;
public static int[] TreeData = new int[MaxSize];
public static int[] RightNode = new int[MaxSize];
public static int[] LeftNode = new int[MaxSize];

public BNTreeArray()
{
int i; // 循環計數變量

for (i = 0; i < MaxSize; i++)
{
TreeData[i] = 0;
RightNode[i] = -1;
LeftNode[i] = -1;
}
}

// ----------------------------------------------------
// 建立二叉樹
// ----------------------------------------------------
public void Create(int Data)
{
int i; // 循環計數變量
int Level = 0; // 樹的階層數
int Position = 0;

for (i = 0; TreeData[i] != 0; i++)
;

TreeData[i] = Data;
while (true) // 尋找節點位置
{
// 判斷是左子樹或是右子樹
if (Data > TreeData[Level])
{
// 右樹是否有下一階層
if (RightNode[Level] != -1)
Level = RightNode[Level];
else
{
Position = -1; // 設定爲右樹
break;
}
}
else
{
// 左樹是否有下一階層
if (LeftNode[Level] != -1)
Level = LeftNode[Level];
else
{
Position = 1; // 設定爲左樹
break;
}
}
}

if (Position == 1) // 建立節點的左右連結
LeftNode[Level] = i; // 連結左子樹
else
RightNode[Level] = i; // 連結右子樹
}

// ---------------------------------------------------------
// 二叉查找法
// ---------------------------------------------------------
public static int BinarySearch(int KeyValue)
{
int Pointer; // 現在的節點位置
int Counter; // 查找次數

Pointer = 0;
Counter = 0;
while (Pointer != -1)
{
Counter++;
// 找到了欲尋找之節點
if (TreeData[Pointer] == KeyValue)
return Counter; // 傳回查找次數
else if (TreeData[Pointer] > KeyValue)
Pointer = LeftNode[Pointer]; // 往左子樹找
else
Pointer = RightNode[Pointer];// 往右子樹找
}
return 0; // 該節點不在此二叉樹中
}
}


總結下:
一 線性查找
又稱順序查找,是從數組的第一個元素開始查找,直到找到待查找元素的位置,直到查找到結果。
最佳的狀況時間是1 ,就是第一個就是待查找的遠射,最差的查找狀況是O(n),就是最後一個是待查找的元素。

二 折半查找
折半查找是將待查找的數組元素不斷的分爲兩部分,每次淘汰二分之一,但是有個大前提是,元素必須是有序的,如果是無序的則要先進行排序操作,這種查找的方法,類似於找英文字典的Java,我們可以一下子找到字母J開頭的,再仔細找。
最佳的狀況時間是1,就是第一次分開就查找到了,最差的查找狀態是O(n),便是待查找的數據出現在最後一次。

三 費氏查找
費氏查找主要是根據費氏數列1 1 2 3 5 8 13 ...... 來確定範圍,然後再進行查找

四 插補查找
插補查找是一種類似折半查找的查找方法,插補查找是以比例的概念,求出待查找數據的可能位置,然後進行比較,如果該值比待查找的小,表示待查找的值可能出現在該值之前的範圍,就這樣一直縮小範圍來確定最終的目標。

五 二叉查找樹
二叉查找樹是先對待查找的數據進行生成樹,確保樹的左分支的值小於右分支的值,然後在就行和每個節點的父節點比較大小,查找最適合的範圍。

這個算法的查找效率很高,但是如果使用這種查找方法要首先創建樹。

以上就是對查找算法的小小總結,在以後的應用中我們應該根據具體的問題具體分析,找到解決問題的最優解決方案。


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