对字符串类型的值进行散列
function HashTable() { this.table = new Array(137);//137——官方比较好的设置数组大小的值 //this.simpleHash = simpleHash; this.betterHash = betterHash; this.showDistro = showDistro; this.put = put; //this.get = get; } /* 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.betterHash(data);//获得数据散列的位置 this.table[pos] = data; } 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 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 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]);//将数组中的数据放入到散列表中 } hTable.showDistro();