Data Structure and Algorithm Analysis----Hash Table

overview

Hash table (Hash table, also called hash table) is a data structure that is directly accessed according to the key value (Key value). That is, it accesses records by mapping key values ​​to a location in the table to speed up lookups. This mapping function is called a hash function, and the array storing the records is called a hash table.
Given a table M, there is a function f(key). For any given key value key, if the address of the record in the table containing the key can be obtained after substituting the function, the table M is called a hash (Hash). table, the function f(key) is a hash (Hash) function.
insert image description here
From Baidu Encyclopedia

Simply put , a hash table is a data structure, a non-linear structure, and a table.
Correspondingly, there is a hash function. Given a value of the hash function, the data corresponding to this value in the table can be quickly found through this function.
So in general, the significance of the existence of the hash table is to speed up the lookup and use it with the hash function.

Generally, we implement hash tables through arrays and linked lists (the specific structure is the same as the above figure). Define an array, and then create several linked lists, the number of created linked lists is equal to the capacity of the array. Then put the linked list in the array, put the data to be stored in the linked list, and thus form a simple hash table.

implement a hash table

Implementing a hash table first requires a linked list

create a linked list

  1. Creating a linked list requires nodes, first we create nodes
    insert image description hereA simple employee class with next, representing the node class
  2. A node is an object, and a linked list is also an object, so we need to create a linked list class.
    This class is a linked list class. The linked list class has several properties and methods. Here we only implement its addition, search and traversal functions.
    insert image description here
    When this linked list is created successfully

Implementation table

insert image description here
The main body of the table is implemented on the above part of the code
First, an array of linked list type, and then one also needs an attribute representing the capacity of the array.
Then the following is the constructor of the table, which receives a parameter, which is used to initialize and create an array, and is also used to add a linked list to the array, and the hash table has been created so far.
But we want to use this data structure, so he must have several basic methods, these methods must be based on the existing methods of the linked list, because this hash table, from the bottom level, we are manipulating after all is the data in the linked list.

Construction and use of a complete hash table

In the use of hash tables, the hash function is extremely important. It is his existence that can make our search faster

hash function

A hash function refers to a function that maps the key key value of an element in a hash table to the storage location of the element.
In general linear tables and trees, the relative position of records in the structure is random, that is, there is no definite relationship with the keywords of the records. Therefore, a series of comparisons with keywords are required when searching for records in the structure . This type of search method is based on "comparison", and the efficiency of search depends on the number of comparisons performed during the search process. Ideally, the desired record can be found directly, so a definite correspondence f must be established between the storage location of the record and its keywords, so that each keyword corresponds to a unique storage location in the structure.
From Baidu Encyclopedia

Simply put , a hash function is a function that exists for the convenience of searching or storing in a hash table. All functions that can improve the lookup speed of the hash table are called hash functions.
Here, we simply write a hash function, write a hash function by taking the remainder of the array capacity according to the employee id number, see below for details

We use the employee id to take the remainder of the array capacity, and choose which linked list to put the employee in according to the data obtained by taking the remainder. The data obtained by taking the remainder must be less than or equal to the maximum index of the array. When the obtained data is the same as a certain index, the employee is placed at the end of the linked list corresponding to the index position, so that some different employees can be evenly placed in different in the list of

The query on the hash table is also similar. First, obtain an index value by taking the remainder, and then locate the linked list corresponding to the index position, and perform a traversal query on that linked list.

Here a simple hash function and
insert image description here
a complete hash table class should have some methods.
We simply add some methods to the hash table according to the methods owned by the linked list:
insert image description here

test


First simply set the array capacity to 6

insert image description here
insert image description here
no problem

all codes

import java.util.Scanner;


//哈希表
//一种数据结构
public class Hashtable {
    
    
    public static void main(String[] args) {
    
    
        HashtableDemo hashtableDemo=new HashtableDemo(6);
        Scanner scanner=new Scanner(System.in);

        while (true) {
    
    
            System.out.println("1,添加\n2,展示\n3,查找\n0,退出");
            String string=scanner.next();
            if (string.equals("1")){
    
    
                int n;
                String name,N;
                while (true){
    
    
                    System.out.print("输入id");
                    N=scanner.next();
                    try {
    
    
                        n= Integer.parseInt(N);
                        System.out.print("输入姓名");
                        name=scanner.next();
                        break;
                    }catch (Exception e){
    
    
                        System.out.println("输入错误,请重新输入");
                    }
                }
                Employee employee=new Employee(n,name);
                hashtableDemo.add(employee);
            }else if (string.equals("2")){
    
    
                hashtableDemo.list();
            }else if (string.equals("3")){
    
    
                    int id;
                    String Id;
                    while (true){
    
    
                        System.out.print("输入id");
                        Id=scanner.next();
                        try {
    
    
                            id= Integer.parseInt(Id);
                            try {
    
    
                                hashtableDemo.Select(id);
                            }catch (Exception e){
    
    
                                System.out.println(e);
                            }
                            break;
                        }catch (Exception e){
    
    
                            System.out.println("输入错误,请重新输入");
                        }
                    }
            }else if (string.equals("0")){
    
    
                return;
            }
        }
    }
}
class HashtableDemo{
    
    
    private LinkdeList[] array;
    private int size;

    public HashtableDemo(int size) {
    
    //初始化哈希表
        this.size=size;
        array=new LinkdeList[size];  //创建数组
        for (int i = 0; i < size; i++) {
    
      //初始化数组
            array[i]=new LinkdeList();
        }
    }

    public void add(Employee employee){
    
      //添加员工
        array[Hashfun(employee.getId())].add(employee);  //经过散列函数处理后,调用链表的增加节点的方法
    }
    public void list(){
    
      //遍历哈希表
        for (int i = 0; i < size; i++) {
    
    
            System.out.print("第"+(i+1)+"行:");
            array[i].list();  //对数组的每个链表调用链表对应的遍历方法
        }
    }
    public int Hashfun(int id){
    
    
        return id%size;
    }  //散列函数

    public void Select(int id){
    
    
        System.out.println(array[Hashfun(id)].get(id));  //经过散列函数处理后,调用链表的查找方法
    }  //查找方法
}
class Employee{
    
      //员工类,即链表节点
    private int id;
    private String name;
    public Employee next=null;

    public int getId() {
    
    
        return id;
    }

    public String getName() {
    
    
        return name;
    }

    public Employee(int id, String name) {
    
    
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
    
    
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
class LinkdeList{
    
      //管理链表的类,等于说,这个类就是链表类,一个这样的对象代表着一条链表
    private Employee head; private Employee temp; private Employee end;
    //三个属性,head是头节点,temp是辅助节点用于遍历链表,end用于记录链表尾,用于后面方便加入数据
    public void add(Employee employee){
    
     //    添加节点
        if (head==null){
    
    
            head=employee;
            end=head;
        }else {
    
    
            end.next=employee;
            end=end.next;
        }
    }
    public void list(){
    
    //    遍历
        temp=head;
        if (head==null){
    
    
            System.out.println("无数据");
        }
        while (temp!=null){
    
    
            System.out.println(temp);
            temp=temp.next;
        }
    }
    public Employee get(int id){
    
    //    查找
        temp=head;
        while (temp!=null){
    
    
            if (temp.getId()==id){
    
    
                return temp;
            }
            temp=temp.next;
        }
        throw new RuntimeException("未找到");
    }
}

Guess you like

Origin blog.csdn.net/qq_45821251/article/details/121069985
Recommended