-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBetterHashTable.html
More file actions
44 lines (42 loc) · 1.24 KB
/
BetterHashTable.html
File metadata and controls
44 lines (42 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<script>
function HashTable(){
this.table = new Array(137); //确保散列表中用来存储数据的数组其大小是个质数,这和计算散列值时使用的取余运算有关
}
HashTable.prototype={
put: function(data){
var pos = this.betterHash(data);
this.table[pos] = data;
},
betterHash: function(data){ //计算字符串中各字符的 ASCII 码值,求和时每次要乘以一个质数
const H = 31;
var total = 0;
for (var i = 0; i < data.length; ++i) {
total += H * total + data.charCodeAt(i);
}
total = total % this.table.length;
if (total < 0) {
total += this.table.length-1;
}
return parseInt(total);
},
showDistro: function(){
console.log(this.table)
var n = 0;
for (var i = 0; i < this.table.length; i++) {
if( this.table[i] != undefined){
document.writeln(i + ": " + this.table[i])
document.writeln("</br>")
}
}
},
get : function(key){
return this.table[this.betterHash(key)]
}
}
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();
</script>