之前对查找算法做的一些简单总结与实现:
查找算法时间复杂度:
1.二分查找的实现(待补充)
2.hash查找算法(哈希函数、解决冲突)
public class HashSerash {
public int hashSearch(int[] hash,int length,int key){
int hashIndex=key%length;
while(hash[hashIndex]!=0&&hash[hashIndex]!=key){
hashIndex=(++hashIndex)%length;//如果不为0且有其他值,则去寻找下一个位置,直到为0或者哈希值等于key值--开放地址解决冲突
}
if(hash[hashIndex]==0)
return -1;
return hashIndex;
}
public void hashInsert(int[] hash,int length,int key){
int hashIndex=key%length;//取余法确定哈希函数
while(hash[hashIndex]!=0){
hashIndex=(++hashIndex)%length;//如果不为0则去寻找下一个位置,直到为0则存储--开放地址解决冲突
}
hash[hashIndex]=key;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array1=new int[]{2,43,321,6,119,5,34,1};
int length=array1.length+3;
int[] hash=new int[length];
for (int i = 0; i < array1.length; i++) {
System.out.print(array1[i]+",");
}
System.out.println("\n");
HashSerash hs=new HashSerash();
for (int i = 0; i < array1.length; i++) {
hs.hashInsert(hash, length, array1[i]);
}
int m=hs.hashSearch(hash, length, 6);
if(m==-1){
System.out.println("不在");
}else{
System.out.println("索引位置:"+m);
}
}
}
原文:http://www.cnblogs.com/jetHu/p/6445117.html