散列碰撞的解决方法——线性探测法(开放寻址法的一种)

    function HashTable() {
        this.table = new Array(137);//137——官方比较好的设置数组大小的值
        this.betterHash = betterHash;
        this.showDistro = showDistro;
        this.put = put;
        //this.get=get;
    }
    function betterHash(data) {
        var cons = 31;//此参数的设置是为了避免碰撞
        var total = 0;
        for ( var i = 0; i < data.length; ++i) {
            total += cons * total + data.charCodeAt(i);
        }
        total = total % this.table.length;
        document.write("Hash value: " + data + " -> " + total + "<br />");//测试是否有相同的散列值
        if (total < 0) {
            total += this.table.length - 1;
        }
        return parseInt(total);
    }
    function put(data) {
        var pos = this.betterHash(data);
        if (this.table[pos] == undefined) {
            this.table[pos] = data;
        } else {
            while (this.table[pos] != undefined) {
                pos++;
            }
            this.table[pos] = data;
        }
    }
    function showDistro() {
        for ( var i = 0; i < this.table.length; ++i) {
            if (this.table[i] != undefined) {
                document.write(i + ": " + this.table[i]);
                document.write("<br />");
            }
        }
    }
    var hTable = new HashTable();
    var someNames = [ "David", "Jennifer", "Donnie", "Raymond", "Cynthia",
            "Mike", "Clayton", "Danny", "Jonathan" ];
    for ( var i = 0; i < someNames.length; ++i) {
        hTable.put(someNames[i]);
    }
    hTable.showDistro();

 

posted @ 2016-04-15 20:54  绯乐  阅读(1832)  评论(0编辑  收藏  举报