您的当前位置:首页HASH查找算法—JAVA实现
HASH查找算法—JAVA实现
来源:锐游网
仅做日常记录,侵权删。 hash查找。构建一个hash表,然后存入对应的数据。 存在问题hash冲突。目前有:拉链法和线性探测法来解决hash冲突。 参考链接: https:///qq_49306008/article/details/120851829
//hash查找。构建一个hash表,然后存入对应的数据。
//存在问题hash冲突。目前有:拉链法和线性探测法来解决hash冲突。
//https:///qq_49306008/article/details/120851829
public static void main(String[] args) {
int[] source = Data.init();
HashTable hashTable = new HashTable(51);
for(int i =0 ;i <source.length ;i++){
hashTable.add(source[i]);
}
//查询数据
hashTable.search(61);
}
public class Entry {
int value;
Entry next;
public Entry(int value){
this.value = value;
this.next = null;
}
}
public class HashNode {
Entry head;
//添加数据
public void add(Entry entry){
if (head == null) {
head = entry;
return;
}
Entry tmp = head;
//尾插法
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = entry;
}
//查找数据
public Entry search(int value){
if (head == null) {
return null;
}
Entry tmp = head;
while (tmp != null) {
if (tmp.value == value) {
return tmp;
}
tmp = tmp.next;
}
return null;
}
}
public class HashTable {
HashNode[] nodeLists;
int size;
public HashTable(int size) {
this.size = size;
nodeLists = new HashNode[size];
for (int i = 0; i < size; i++) {
nodeLists[i] = new HashNode();
}
}
public void add(int value) {
Entry entry = new Entry(value);
int hashIndex = hash(value);
//将数据添加到对应的链表中。
nodeLists[hashIndex].add(entry);
}
public void search(int value) {
int hashIndex = hash(value);
//将数据添加到对应的链表中。
Entry node = nodeLists[hashIndex].search(value);
if (node != null) {
System.out.println("在第" + (hashIndex + 1) + "条链表中找到。 :" + value);
} else {
System.out.println("未找到数据");
}
}
//编写一个散列函数(哈希函数),使用一个简单的取模法
private int hash(int value) {
return value % size;
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容