zoukankan      html  css  js  c++  java
  • 散列表,散列函数,碰撞处理解决:线性探测法

    散列表,散列函数,碰撞处理解决:线性探测法
    /*
    * 散列表,散列函数,碰撞处理解决:线性探测法
    * 原理:散列表位置碰撞时,检查散列表下一个位置是否为空,为空就存入数据;不为空,继续检测下一个位置。
    * 直到找到一个空的位置为止。
    * 当数组的大小是要存储的数据两倍以上时,线性探测法比开链法好
    *
    * */
    function HashTable() {
        this.table = new Array(137);
        this.values = [];
        this.betterHash = betterHash;
        this.showDistro = showDistro;
        this.put = put;
        this.get = get;
    }
    
    // put for linear probing
    function put(key, data) {
        var pos = this.betterHash(key);
        if (this.table[pos] == undefined) {
            this.table[pos] = key;
            this.values[pos] = data;
        }else{
            while (this.table[pos] != undefined) {
                pos++;
            }
            this.table[pos] = key;
            this.values[pos] = data;
        }
    }
    
    function betterHash(string) {
        const H = 37;
        var total = 0;
        for (var i = 0; i < string.length; ++i) {
            total += H * total + string.charCodeAt(i);
        }
        total = total % this.table.length;
        if (total < 0) {
            total += this.table.length-1;
        }
        return parseInt(total);
    }
    
    function showDistro() {
        for (var i = 0; i < this.table.length; ++i) {
            if (this.table[i] != undefined) {
                console.log(this.table[i] + ": " + this.values[i]);
            }
        }
    }
    
    // get for linear probing
    function get(key) {
        var hash = this.betterHash(key);
    
        for (var i = hash; this.table[hash] != undefined; i++) {
            if (this.table[hash] == key) {
                console.log("查找到的键值为: "+this.values[hash]);
                return this.values[hash];
            }
        }
    
        console.log("无该键值!");
        return undefined;
    }
    
    /*测试线性探测法*/
    var someNames = ["David", "Jennifer", "Donnie", "Raymond",
        "Cynthia", "Mike", "Clayton", "Danny", "Jonathan"];
    var hTable = new HashTable();
    for (var i = 0; i < someNames.length; ++i) {
        hTable.put(someNames[i],someNames[i]);
    }
    hTable.showDistro();
    hTable.get("Jennifer");
  • 相关阅读:
    Text box to accept only number
    两个经典的Oracle触发器示例
    ELK部署
    Win10+CentOS7双系统引导修复
    自定义多选框(checkbox)和单选框(radio)css样式
    js事件
    js数组与字符串处理 slice、splice、substring、substr、push、pop、shift、reverse、sort、join、split
    css入门基础
    cocos2dx基础篇(7) 触碰事件
    cocos2dx基础篇(6) 定时器schedule/update
  • 原文地址:https://www.cnblogs.com/baiyangyuanzi/p/6692815.html
Copyright © 2011-2022 走看看