码迷,mamicode.com
首页 > 其他好文 > 详细

散列碰撞问题的解决——开链法(拉链法)

时间:2016-04-15 21:53:12      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:

    function HashTable() {
        this.table = new Array(137);//137——官方比较好的设置数组大小的值
        this.buildChains = buildChains;
        this.simpleHash = simpleHash;
        this.showDistro = showDistro;
        this.put = put;
        //this.get=get;
    }
    function buildChains() {//核心方法
        for ( var i = 0; i < this.table.length; ++i) {
            this.table[i] = new Array();
        }
    }
    function simpleHash(data) {
        var total = 0;
        for ( var i = 0; i < data.length; ++i) {
            total += data.charCodeAt(i);
        }
        return total % this.table.length;
    }
    function put(data) {
        var pos = this.simpleHash(data);
        var index = 0;
        if (this.table[pos][index] == undefined) {
            this.table[pos][index] = data;
        } else {
            while (this.table[pos][index] != undefined) {
                ++index;
            }
            this.table[pos][index] = data;
        }
    }
    function showDistro() {
        for ( var i = 0; i < this.table.length; ++i) {
            if (this.table[i][0] != undefined) {
                document.write(i + ": " + this.table[i]);
                document.write("<br />");
            }
        }
    }
    var hTable = new HashTable();
    hTable.buildChains();
    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();
    /*上述程序运行结果为:
    35: Cynthia
    45: Raymond,Clayton
    57: Donnie
    77: David
    95: Danny
    116: Mike
    132: Jennifer
    134: Jonathan*/

 

散列碰撞问题的解决——开链法(拉链法)

标签:

原文地址:http://www.cnblogs.com/feile/p/5396773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!