五大经典查找算法
- 顺序查找
- 折半查找
- 哈希查找
- 索引查找
- 二叉树树查找
线性查找,通过代码遍历,一个一个比较
核心算法
//顺序查找
public static int orderLookup(int[] list, int key) {
for (int i = 0; i < list.length; i++) {
if (list[i] == key) {
return i;
}
}
return -1;
}
折半查找(只能用于有顺序的数组)
将需要查找的数与数组的中值进行比较,若小于,right指针左移,大于则右移,每次排除一半的数。
//折半查找-----适用于有顺序的查找
public static int halveLookup(int[] list, int key) {
int low = 0, high = list.length - 1;
while (low <= high) {
int middle = (low + high) / 2;
//
if (list[middle] == key) {
return middle;
}
//值在前半段
else if (key < list[middle]) {
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}
哈希查找—建立hash函数,通过自己的规则将数存入数组地址里面,当需要查找该数的时候,计算出该数在数组地址的位置,直接查询,这里需要注意的是处理hash冲突(当该地址已经被使用,寻找附近没被使用的地址进行存储)
//哈希查找,通过hash算法,在hash表里面进行查找
//测试hash查找
public static void testHash(int[] list,int length,int key){
//插入hash表
for (int i=0;i<list.length-1;i++){
insertHash(length,list[i]);
}
//hash查找
int index = searchHash(hash, length, key);
if (index!=-1){
System.out.println("hash查找索引位置为"+index);
}
else {
System.out.println("不在哈希表中");
}
}
//查找hash
public static int searchHash(int[] list, int length, int key) {
int hashAddress = key % length;
while (list[hashAddress] != 0 && list[hashAddress] != key) {
hashAddress = (++hashAddress) % length;
}
if (list[hashAddress] == 0) {
return -1;
}
return hashAddress;
}
//插入哈希表,通过取余法插入,通过开放寻址法解决冲突
public static void insertHash( int length, int key) {
int hashAddress = key % length;
//解决冲突
while (hash[hashAddress] != 0) {
hashAddress = (++hashAddress) % length;
}
//放入字典
hash[hashAddress] = key;
}
最后两种查找—索引查找与二叉树查找,理解倒是理解了,就是在代码的实现上有点问题,怪自己太菜了,这里就不做记录了。如果有什么不清楚可以去看看我参考的老哥的博客,很棒。另附上代码地址:https://gitee.com/zhoujie1/studyTest.git
参考博客:
https://www.cnblogs.com/huangxincheng/archive/2011/11/20/2256351.html
https://www.cnblogs.com/huangxincheng/archive/2011/11/24/2261074.html
https://www.cnblogs.com/huangxincheng/archive/2011/11/27/2265427.html