js数据结构之hash散列的详细实现方法

hash散列中需要确定key和value的唯一确定关系。

hash散列便于快速的插入删除和修改,不便于查找最大值等其他操作

以下为字符和数字的hash散列:

function HashTable () {
    this.table = new Array(137);
    this.value = new Array();
    this.simpleHash = simpleHash;
    this.betterHash = betterHash;
    this.display = display;
    this.put = put;
    this.get = get;
    this.buildChains = buildChains; // 开链法解决碰撞
}

function simpleHash (data) {
    var total = 0;
    for(var i =0; i<data.length; i++){
        total= total + data.charCodeAt(i);
    }
    return total % this.table.length;
}

function betterHash (data) {
    var total = 0;
    const h = 37; // 挑选合适的质数
    data = data.toString();
    for(var i=0;i<data.length; i++){
        total = total*h + data.charCodeAt(i);
    }
    total = total % this.table.length;
    if(total<0) {
        return total+=this.table.length-1;
    }
    return parseInt(total);
}

function put (key, value) {
    var pos = this.betterHash(key);
    if(this.table[pos] === undefined){
        this.table[pos] = key;
        this.value[pos] = value;
    }else{
        while(this.table[pos]!==undefined){
            pos++
        }
        this.table[pos] = key;
        this.value[pos] = value;
    }
}

function get(key) {
   var hash = -1;
   hash = this.betterHash(key);
   if (hash > -1) {
      for (var i = hash; this.table[hash] != undefined; i++) {
         if (this.table[hash] == key) {
            return this.value[hash];
         }
      }
   }
   return undefined;
}

function display () {
    var _this = this;
    this.value.forEach(function(item, index){
        if (item!==undefined) {
            console.log(_this.table[index] + ": " + item);
        }
        
    })
}

function buildChains () {
    this.table.forEach(function (item, index) {
        item = new Array();
    })
}

hash的使用方法:

function buildChains () {
    this.table.forEach(function (item, index) {
        item = new Array();
    })
}

var someNames = ["David", "Jennifer", "Donnie", "Raymond","Cynthia", "Mike", "Clayton", "Danny", "Jonathan", "Donnie"];

var hs = new HashTable();
someNames.forEach(function(item, index){
    hs.put(item, item + "Val")
})
hs.display();

console.log(hs.get("David"))

 

转载于:https://www.cnblogs.com/pomelott/p/9478394.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值