Day_42哈希表

news2024/10/6 9:28:08

目录

一. 关于哈希表

二. 如何实现哈希表

        1. 散列函数

        2. 散列表

        3. 散列函数的构造方法

        4. 处理冲突的方法

三. 代码实现

        1. 构造函数构造哈希表

        2. 哈希表的查找

四. 代码展示

五. 数据测试​编辑

六. 总结


一. 关于哈希表

        在前面介绍的线性表的查找中,记录在表中的位置与记录的关键字之间不存在确定关系,因此,在这些表中查找记录时需进行一系列的关键字比较。这类查找方法建立在“比较”的基础上,查找的效率取决于比较的次数。

二. 如何实现哈希表

        1. 散列函数

        一个把查找表中的关键字映射成该关键字对应的地址的函数,记为Hash(key)=Addr(这里的地址可以是数组下标、有索引或内存地址等)。散列函数可能会把两个或两个以上的不同关键字映射到同一地址,称这种情况为冲突,这些发生碰撞的不同关键字称为同义词。一方面, 设计得好的散列函数应尽量减少这样的冲突;另一方面,由于这样的冲突总是不可避免的,所以还要设计好处理冲突的方法。

        2. 散列表

        根据关键字而直接进行访问的数据结构。也就是说,散列表建立了关键字和存储地址之间的一种直接映射关系。理想情况下,对散列表进行查找的时间复杂度为0(1),即与表中元素的个数无关。下面分别介绍常用的散列函数和处理冲突的方法。

构造完成的哈希表

        3. 散列函数的构造方法

        1)散列函数的定义域必须包含全部需要存储的关键字,而值域的范围则依赖于散列表的大小或地址范围。

        2)散列函数计算出来的地址应该能等概率。均匀的分布在整个地址空间中,从而减少冲突的发生。

        3)散列函数应尽量简单,能够在较短的时间内计算出任意一个关键字对应的散列地址。

        以下是常用的散列函数:

        H(key)=a\times key+b

H(key)=key\%p

        4. 处理冲突的方法

        线性探测法:冲突发生时,顺序查看表中下一个单元(探测到表尾地址m-1时,下一个探测地址是表首地址0),直到找出下一个空闲单元(当表未填满时一定能找到一个空闲单元)或查遍全表。线性探测法可能使第i个散列地址的同义词存入第i+1个散列地址,这样本应该存入i+1个散列地址的元素就争夺i+2个散列地址的元素地址...从而造成大量元素在相邻的散列地址上堆积起来,大大降低了查找效率。

        除此之外再介绍一种拉链法处理冲突:当我们的同义词发生冲突之后,可以把所有的同义词存储在一个线性链表中,这个线性链表由其散列地址唯一标识。假设散列地址i的同义词链表的头指针存放在散列表的第i个单元中,因而查找、插入、删除操作主要在同义词链中进行。例如散列函数Hash(key)=key%13,用拉链法处理冲突建立如下的哈希表

        

拉链法处理冲突

        还有平方探测法,双散列法,伪随机探测法在这里就不一一赘述。

三. 代码实现

        1. 构造函数构造哈希表

        在这里设置了一个新的构造函数,传入标签数组paraKeyArray,对应的数据数组paraContentArray,还有哈希表长度paraLength。构造一个长度为paraLength的数组,每个位置上是用哈希函数得到的节点值。

    /**
     *********************
     * The second constructor. For Hash code only. It is assumed that
     * paraKeyArray.length <= paraLength.
     *
     * @param paraKeyArray     The array of the keys.
     * @param paraContentArray The array of contents.
     * @param paraLength       The space for the Hash table.
     *********************
     */
    public DataArray(int[] paraKeyArray, String[] paraContentArray, int paraLength) {
        // Step 1. Initialize.
        length = paraLength;
        data = new DataNode[length];

        for (int i = 0; i < length; i++) {
            data[i] = null;
        } // Of for i

        // Step 2. Fill the data.
        int tempPosition;

        for (int i = 0; i < paraKeyArray.length; i++) {
            // Hash.
            tempPosition = paraKeyArray[i] % paraLength;

            // Find an empty position
            while (data[tempPosition] != null) {
                tempPosition = (tempPosition + 1) % paraLength;
                System.out.println("Collision, move forward for key " + paraKeyArray[i]);
            } // Of while

            data[tempPosition] = new DataNode(paraKeyArray[i], paraContentArray[i]);
        } // Of for i
    }// Of the second constructor

        2. 哈希表的查找

        构建完成哈希表之后,开始查找,输入需要查找的标签i,先查找i%paraLength的位置是不是i;若不是则将i自加1,再用(i+1)%paraLength查找第二个位置;继续如上循环直到查找到为止。

    /**
     *********************
     * Hash search.
     *
     * @param paraKey The given key.
     * @return The content of the key.
     *********************
     */
    public String hashSearch(int paraKey) {
        int tempPosition = paraKey % length;
        while (data[tempPosition] != null) {
            if (data[tempPosition].key == paraKey) {
                return data[tempPosition].content;
            } // Of if
            System.out.println("Not this one for " + paraKey);
            tempPosition = (tempPosition + 1) % length;
        } // Of while

        return "null";
    }// Of hashSearch

四. 代码展示

        主类

package Day_42;

import Day_41.DataArray;

public class demo1 {
    /**
     *********************
     * The entrance of the program.
     *
     * @param args Not used now.
     *********************
     */
    public static void main(String args[]) {
//        System.out.println("\r\n-------sequentialSearchTest-------");
        int []paraKeyArray;
        paraKeyArray=new int[]{1,2,3};
        String[] paraContentArray = new String[]{"121","21","324"};
        DataArray test=new DataArray(paraKeyArray,paraContentArray);

        test.hashSearchTest();


    }// Of main

}

        调用类:

package Day_41;
/**
 * Data array for searching and sorting algorithms.
 *
 * @author Jian An 2569222191@qq.com.
 */
public class DataArray {
    /**
     * An inner class for data nodes. The text book usually use an int value to
     * represent the data. I would like to use a key-value pair instead.
     */
    class DataNode {
        /**
         * The key.
         */
        int key;

        /**
         * The data content.
         */
        String content;

        /**
         * ********************
         * The first constructor.
         * ********************
         */
        DataNode(int paraKey, String paraContent) {
            key = paraKey;
            content = paraContent;
        }// Of the first constructor

        /**
         * ********************
         * Overrides the method claimed in Object, the superclass of any class.
         * ********************
         */
        public String toString() {
            return "(" + key + ", " + content + ") ";
        }// Of toString
    }// Of class DataNode

    /**
     * The data array.
     */
    DataNode[] data;

    /**
     * The length of the data array.
     */
    int length;

    /**
     * ********************
     * The first constructor.
     *
     * @param paraKeyArray     The array of the keys.
     * @param paraContentArray The array of contents.
     *                         ********************
     */
    public DataArray(int[] paraKeyArray, String[] paraContentArray) {
        length = paraKeyArray.length;
        data = new DataNode[length];

        for (int i = 0; i < length; i++) {
            data[i] = new DataNode(paraKeyArray[i], paraContentArray[i]);
        } // Of for i
    }// Of the first constructor

    /**
     * ********************
     * Overrides the method claimed in Object, the superclass of any class.
     * ********************
     */
    public String toString() {
        String resultString = "I am a data array with " + length + " items.\r\n";
        for (int i = 0; i < length; i++) {
            resultString += data[i] + " ";
        } // Of for i

        return resultString;
    }// Of toString

    /**
     * ********************
     * Sequential search. Attention: It is assume that the index 0 is NOT used.
     *
     * @param paraKey The given key.
     * @return The content of the key.
     * ********************
     */
    public String sequentialSearch(int paraKey) {
        data[0].key = paraKey;

        int i;
        // Note that we do not judge i >= 0 since data[0].key = paraKey.
        // In this way the runtime is saved about 1/2.
        // This for statement is equivalent to
        //for (i = length - 1; data[i].key != paraKey; i--);
        for (i = length - 1; data[i].key != paraKey; i--) {
            ;
        }//Of for i
        return data[i].content;
    }// Of sequentialSearch

    /**
     * ********************
     * Test the method.
     * ********************
     */
    public static void sequentialSearchTest() {
        int[] tempUnsortedKeys = {-1, 5, 3, 6, 10, 7, 1, 9};
        String[] tempContents = {"null", "if", "then", "else", "switch", "case", "for", "while"};
        DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);

        System.out.println(tempDataArray);

        System.out.println("Search result of 10 is: " + tempDataArray.sequentialSearch(10));
        System.out.println("Search result of 5 is: " + tempDataArray.sequentialSearch(5));
        System.out.println("Search result of 4 is: " + tempDataArray.sequentialSearch(4));
    }// Of sequentialSearchTest

    /**
     * ********************
     * Binary search. Attention: It is assume that keys are sorted in ascending
     * order.
     *
     * @param paraKey The given key.
     * @return The content of the key.
     * ********************
     */
    public String binarySearch(int paraKey) {
        int tempLeft = 0;
        int tempRight = length - 1;
        int tempMiddle = (tempLeft + tempRight) / 2;

        while (tempLeft <= tempRight) {
            tempMiddle = (tempLeft + tempRight) / 2;
            if (data[tempMiddle].key == paraKey) {
                return data[tempMiddle].content;
            } else if (data[tempMiddle].key <= paraKey) {
                tempLeft = tempMiddle + 1;
            } else {
                tempRight = tempMiddle - 1;
            }
        } // Of while

        // Not found.
        return "null";
    }// Of binarySearch

    /**
     * ********************
     * Test the method.
     * ********************
     */
    public static void binarySearchTest() {
        int[] tempSortedKeys = {1, 3, 5, 6, 7, 9, 10};
        String[] tempContents = {"if", "then", "else", "switch", "case", "for", "while"};
        DataArray tempDataArray = new DataArray(tempSortedKeys, tempContents);

        System.out.println(tempDataArray);

        System.out.println("Search result of 10 is: " + tempDataArray.binarySearch(10));
        System.out.println("Search result of 5 is: " + tempDataArray.binarySearch(5));
        System.out.println("Search result of 4 is: " + tempDataArray.binarySearch(4));
    }// Of binarySearchTest


    /**
     *********************
     * The second constructor. For Hash code only. It is assumed that
     * paraKeyArray.length <= paraLength.
     *
     * @param paraKeyArray     The array of the keys.
     * @param paraContentArray The array of contents.
     * @param paraLength       The space for the Hash table.
     *********************
     */
    public DataArray(int[] paraKeyArray, String[] paraContentArray, int paraLength) {
        // Step 1. Initialize.
        length = paraLength;
        data = new DataNode[length];

        for (int i = 0; i < length; i++) {
            data[i] = null;
        } // Of for i

        // Step 2. Fill the data.
        int tempPosition;

        for (int i = 0; i < paraKeyArray.length; i++) {
            // Hash.
            tempPosition = paraKeyArray[i] % paraLength;

            // Find an empty position
            while (data[tempPosition] != null) {
                tempPosition = (tempPosition + 1) % paraLength;
                System.out.println("Collision, move forward for key " + paraKeyArray[i]);
            } // Of while

            data[tempPosition] = new DataNode(paraKeyArray[i], paraContentArray[i]);
        } // Of for i
    }// Of the second constructor

    /**
     *********************
     * Hash search.
     *
     * @param paraKey The given key.
     * @return The content of the key.
     *********************
     */
    public String hashSearch(int paraKey) {
        int tempPosition = paraKey % length;
        while (data[tempPosition] != null) {
            if (data[tempPosition].key == paraKey) {
                return data[tempPosition].content;
            } // Of if
            System.out.println("Not this one for " + paraKey);
            tempPosition = (tempPosition + 1) % length;
        } // Of while

        return "null";
    }// Of hashSearch

    /**
     *********************
     * Test the method.
     *********************
     */
    public static void hashSearchTest() {
        int[] tempUnsortedKeys = { 16, 33, 38, 69, 57, 95, 86 };
        String[] tempContents = { "if", "then", "else", "switch", "case", "for", "while" };
        DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents, 19);

        System.out.println(tempDataArray);

        System.out.println("Search result of 95 is: " + tempDataArray.hashSearch(95));
        System.out.println("Search result of 38 is: " + tempDataArray.hashSearch(38));
        System.out.println("Search result of 57 is: " + tempDataArray.hashSearch(57));
        System.out.println("Search result of 4 is: " + tempDataArray.hashSearch(4));
    }// Of hashSearchTest

}// Of class DataArray

五. 数据测试

六. 总结

        这一小节的代码比较简单,这一节的知识体现不在代码上,而在于构造哈希函数,处理冲突方法的结构上。一个好的哈希表处理查找的效率是O(1),即瞬间可以得到传入标签的数据值,这在我们无论哪一个查找算法中无疑都是最快的。但是缺点也还是有的,若构造哈希函数没有构造好,或者冲突的没有处理好,那将造成大范围的“聚集”现象,大大降低查找效率。

        除此之外,现目前很多的编程环境已经自带了哈希表的包,例如哈希表在JDK中有不少的实现,例如HahsMapHashTable等,对哈希表感兴趣的可以阅读本文后去查看JDK的相应实现,相信这可以增强你对哈希表的理解。

        

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/617893.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

RabbitMQ入门案例之Simple简单模式

RabbitMQ入门案例之Simple简单模式 前言什么是Simple模式Simple模式操作RabbitMQ管理界面的部分介绍 前言 本文将介绍RabbitMQ的七种工作模式的第一种Simple模式的代码实现&#xff0c;编程工具使用的是IDEA&#xff0c;在RabbitMQ中的工作模式都是生产消费模型 生产者消费模型…

Android系统的Ashmem匿名共享内存子系统分析(4)- Ashmem子系统的 Java访问接口

声明 其实对于Android系统的Ashmem匿名共享内存系统早就有分析的想法&#xff0c;记得2019年6、7月份Mr.Deng离职期间约定一起对其进行研究的&#xff0c;但因为我个人问题没能实施这个计划&#xff0c;留下些许遗憾…文中参考了很多书籍及博客内容&#xff0c;可能涉及的比较…

【云原生】Docker镜像的创建

1.Dokcer镜像的创建 创建镜像有三种方法&#xff0c;分别为【基于已有镜像创建】、【基于本地模板创建】以及【基于Dockerfile创建】。 1.1 基于现有镜像创建 &#xff08;1&#xff09;首先启动一个镜像&#xff0c;在容器里做修改 docker run -it --name web centos:7 /…

2023年6月 国内大语言模型对比【国内模型正在崛起】

先说一下这个文章怎么来的。因为朋友问我大语言模型可以生成公务员面试回答不&#xff0c;我说可以啊。之前看文心有这个服务。我想最近好几个模型也没用了测一把&#xff01;结果&#xff01;大吃一惊&#xff01;我觉得我的三个傻孩子长大了&#xff01;&#xff08;chatglm1…

chatgpt赋能python:Python如何降低版本:提升代码兼容性与SEO效果

Python如何降低版本&#xff1a;提升代码兼容性与SEO效果 在大多数情况下&#xff0c;使用Python的最新版本是最好的选择。新版本通常提供更好的性能和更多的功能&#xff0c;同时也有更好的安全性和稳定性。然而&#xff0c;有些情况下&#xff0c;我们需要运行旧版本的Pytho…

chatgpt赋能python:Python字体如何调大?一篇全面的教程

Python字体如何调大&#xff1f;一篇全面的教程 什么是Python&#xff1f; Python是一种高级编程语言&#xff0c;一般被用于Web开发、数据分析和人工智能等领域。其编写简单、易读易学易维护&#xff0c;因此被广泛使用。 为什么要调大Python字体&#xff1f; 在Python编程…

imagine 关键词绘图( Midjourney )

前几天从网上看到的imagine 关键词绘图( Midjourney )&#xff0c;感觉挺好用&#xff0c;分享给大家&#xff1a; 一、基本关键词: 一个基本的提示可以简单到一个单词、短语或表情符号。 二、高级关键词: 可以包括一个或多个图像链接、多个文本短语或单词&#xff0c;以及…

内网安全:隧道技术详解

目录 隧道技术 反向连接技术 反向连接实验所用网络拓扑图及说明 网络说明 防火墙限制说明 实验前提说明 实战一&#xff1a;CS反向连接上线 - 拿下Win2008 一. 使用转发代理上线创建监听器 二. 上传后门执行上线 隧道技术 - SMB协议 SMB协议介绍 实战二&#xff1a…

chatgpt赋能python:Python安装到C盘有什么方便之处?

Python安装到C盘有什么方便之处&#xff1f; 在进行Python编程时&#xff0c;安装Python到C盘是一个非常常见的做法。那么&#xff0c;将Python安装到C盘有哪些好处呢&#xff1f;下面&#xff0c;让我们来一一介绍。 1. 方便快捷 安装Python到C盘的好处之一就是非常方便&am…

chatgpt赋能python:Python安装etree:提高XML处理效率的关键

Python安装etree&#xff1a;提高XML处理效率的关键 在Python开发中&#xff0c;XML是一种常用的数据格式。然而&#xff0c;Python标准库自带的ElementTree在大规模数据处理时可能会出现效率低下的情况。因此&#xff0c;我们可以使用第三方模块etree来提高XML处理的效率。 …

案例37:基于Springboot旅游网站系统开题报告设计

博主介绍&#xff1a;✌全网粉丝30W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专…

Linux内核文件读取流程

本文代码基于Linux5.10。 当上层调用read函数读取一个文件时&#xff0c; Linux 内核究竟如何处理&#xff1f; 本文主要介绍这个问题 数据结构 address_space linux 的文件在磁盘上可能是不连续的&#xff0c; 但文件读取又需要将文件当成一个连续的字节流&#xff0c; 为…

大学物理(上)-期末知识点结合习题复习(1)——运动的描述(两类运动学知识点、圆周运动知识点、相对运动知识点)

目录 运动的描述 两类运动知识点 题1 题目描述 题解 题2&#xff08;第一类问题&#xff09; 题目描述 题解 题3&#xff08;第二类问题&#xff09; 题目描述 题解 题4 题目描述 题解 圆周运动知识点 题5 题目描述 题解 相对运动知识点 题6 题目描述…

【通知】关于SRRC认证无线电发射设备型号核准的通知

关于SRRC认证 无线电发射设备型号核准简称型号核准或SRRC&#xff0c;由工业和信息化部无线电管理局受理&#xff0c;中华人民共和国工业和信息化部审批发证。型号核准是指在无线电发射设备投入使用前的研制、生产、进口、购置等环节&#xff0c;对其频谱参数技术指标依法进行…

图文直播功能(互动功能接收端JS-SDK)

图文直播 功能概述 图文直播&#xff0c;即用直播画面与说明文字的形式&#xff0c;以时间轴方式完整详细地记录整场活动/课堂。 当用户错过直播的开始时间&#xff0c;中途进入直播&#xff0c;可通过图文直播的记录对错过的直播进行回顾了解&#xff0c;实现直播信息的有效…

【SpringBoot】SpringBoot Controller接收参数的常用方式

在Controller中加入RestController&#xff0c;效果等于Controller ResponseBody。 1 请求路径参数 直接把表单里面的参数写进 Controller 相应方法的形参中去&#xff0c;这个获取参数的方法适合get提交&#xff0c;而不适合post提交。 PathVariable获取(这个当然不分get和…

Flask学习笔记(1)创建RESTful API

从本文起&#xff0c;笔者将会更新一系列Flask学习笔记。   本文将会讲述在Flask中如何创建RESTful API。在此之前&#xff0c;我们有必要了解下什么是RESTful架构。 RESTful架构 RESTful架构自从2000年被Roy Feilding提出后就受到广泛关注&#xff0c;并被成功地应用于成千…

美国同事的那些离职类型

这次公司的裁员是教科书基本的真的是没错。 但是美国同事的心态和离职类型也让人打开眼界。 后来在公司同事建立的被裁群中才了解到&#xff0c;PM 组也是重灾区&#xff0c;也超过了 50%&#xff0c;不少在公司工作超过 5 年的 PM 都被毫不留情的裁掉了。 就算这次勉勉强强被…

怎么实现常用网络接口自动化测试框架应用?

一、RESTful&#xff08;resource representational state transfer)类型接口测试 (一&#xff09;GUI界面测试工具&#xff1a;jmeter 1、添加线程组 2、添加http请求 3、为线程组添加察看结果树 4、写入接口参数并运行 5、在查看结果树窗口查看结果 6、多组数据可增加CSVDat…

达梦主备守护集群介绍

DM数据守护一主一备或一主多备是一种集成化的高可用、高性能数据库解决方案&#xff0c;是数据库异地容灾的首选方案。通过部署 DM 数据守护&#xff0c;可以在硬件故障&#xff08;如磁盘损坏&#xff09;、自然灾害&#xff08;地震、火灾&#xff09;等极端情况下&#xff0…