# 常见查找算法(Java实现)

### 查找的性能分析：

ASL=i=1nPiCi

i=1nPi=1
Ci $C_i$为找到表中关键字与给定值相等的第i个记录时，和给定值已经进行过比较的关键字个数。

### 静态表查找

#### 顺序查找：

public class OrderSearch {

public static void main(String[] args) {
int[] table = {1,23,4,5,6};
System.out.println(OrderSearch.orderSearch(table, 5));

}

/**
* 顺序查找
* @param table
* @param keyWord
* @return
*/
public static boolean orderSearch(int[] table,int keyWord){
for(int i = 0;i<table.length;i++){
if(table[i] == keyWord){
return true;
}
}
return false;
}

}

#### 折半查找（针对有序序列）：

public class BinarySearch {

public static void main(String[] args) {
int[] table = {2,4,5,6,7,8,9,10};
System.out.println(BinarySearch.binarySearch(table, 20));

}

public static boolean binarySearch(int[] table ,int keyWord){
int low = 0;
int height = table.length-1;
int mid;
while(low<=height){
mid = (low+height)/2;
if(table[mid]> keyWord){
height = mid-1;
}else if(table[mid]<keyWord){
low = mid+1;
}else if(table[mid] == keyWord){
return true;
}
}
return false;
}

}


#### 斐波那契查找（针对有序序列）：

public class FibonacciSearch {

public static void main(String[] args) {
int[] table = {1,2,3,4,5,6,7,8,9,10,11,12,13,14};
for(int i = 0;i<table.length;i++){
System.out.println("表中记录为"+table[i]+"\t,查询结果为"+FibonacciSearch.fibonacciSearch(table, table[i])+"\n");
}

for(int i = 0;i<5;i++){
int ran = new Random().nextInt(100)+14;
System.out.println("关键字为："+ran+"查询结果为"+FibonacciSearch.fibonacciSearch(table, ran)+"\n");
}

}

public static boolean fibonacciSearch(int[] table,int keyWord){
//确定需要的斐波那契数
int i = 0;
while(getFibonacci(i)-1 == table.length){
i++;
}
//开始查找
int low = 0;
int height = table.length-1;
while(low<=height){
int mid = low + getFibonacci(i-1);
if(table[mid] == keyWord){
return true;
}else if(table[mid]>keyWord){
height = mid-1;
i--;
}else if(table[mid]<keyWord){
low = mid+1;
i-=2;
}
}
return false;
}

/**
* 得到第n个斐波那契数
* @return
*/
public static int getFibonacci(int n){
int res = 0;
if(n == 0){
res = 0;
}else if(n == 1){
res = 1;
}else{
int first = 0;
int second = 1;
for(int i = 2;i<=n;i++){
res = first+second;
first = second;
second = res;
}
}
return res;
}
}


### 动态表查找

#### 二叉排序树（二叉查找树）：

• 若他的左子树不为空，则左子树上所有结点的值均小于其根节点的值

• 若他的右子树不为空，则右子树上所有结点的值均大于其根节点的值

• 他的左右子树也均是二叉排序树

http://blog.csdn.net/evankaka/article/details/48088241

03-21 6962

01-13 2630
02-26 2万+
03-18 224
05-28 459
02-08 1430
04-26 229
07-17 7539
07-13 68
10-19 2336
07-31 1182
03-06
11-24 583
02-13 182
02-07 2668
07-08 47
07-27 7132