散列表,散列函数,碰撞处理解决:线性探测法

散列表,散列函数,碰撞处理解决:线性探测法
/*
* 散列表,散列函数,碰撞处理解决:线性探测法
* 原理:散列表位置碰撞时,检查散列表下一个位置是否为空,为空就存入数据;不为空,继续检测下一个位置。
* 直到找到一个空的位置为止。
* 当数组的大小是要存储的数据两倍以上时,线性探测法比开链法好
*
* */
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");

 

    原文作者:算法小白
    原文地址: https://www.cnblogs.com/baiyangyuanzi/p/6692815.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞