admin管理员组

文章数量:821294

HASH查找算法—JAVA实现

仅做日常记录,侵权删。hash查找。构建一个hash表,然后存入对应的数据。
存在问题hash冲突。目前有:拉链法和线性探测法来解决hash冲突。参考链接:

    //hash查找。构建一个hash表,然后存入对应的数据。//存在问题hash冲突。目前有:拉链法和线性探测法来解决hash冲突。// 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;}}

本文标签: HASH查找算法JAVA实现