function HashTable(){
//用一个数组来存储数据
this.storage = []
//记录表长
this.limit = 7
//记录存放数据的个数
this.count = 0
//哈希函数的的封装
HashTable.prototype.hashFunc = function(str,max){
let hashCode = 0;
for(let i = 0;i<str.length;i++){
hashCode = hashCode * 31 + str.charCodeAt(i)
//循环后
//((str.charCodeAt(0))*32 + str.charCodeAt(1))32秦九韶算法
}
//将这个很大的数转化为一个小数
hashCode = hashCode % max
return hashCode
}
//存入和修改数据
HashTable.prototype.put = function(key,value){
let index = this.hashFunc(key,this.limit)
let bucket = this.storage[index]
if(bucket === undefined){
//如果不设置bucket为一个数组那么bucket是一个undefind接下来的代码没办法走
bucket = []
this.storage[index] = bucket
}
//判断是否需要修改数据修改数据
for(let i = 0;i<bucket.length;i++){
let tuple = bucket[i]
if(tuple[0] === key){
tuple[1] = value
return
}
}
bucket.push([key,value])
this.count++
//判断是否需要扩容
if(this.count > 0.75 * this.limit){
let prime = this.get(this.limit * 2)
this.resize(prime)
}
}
//查看操作
HashTable.prototype.get = function(key){
let index = this.hashFunc(key,this.limit)
let bucket = this.storage[index]
if(bucket === undefined) return undefined
for (let i = 0;i < bucket.length;i++) {
let tuple = bucket[i]
if(tuple[0] === key){
return tuple[1]
}
}
return undefined
}
//删除操作
HashTable.prototype.remove = function(key){
let index = this.hashFunc(key,this.limit)
let bucket = this.storage[index]
if(bucket === undefined)return undefined
for(let i = 0;i<bucket.length;i++){
let tuple = bucket[i]
if(tuple[0] === key){
bucket.splice(i,1)
this.count--
return tuple[1]
}
}
//判断是否要减少容量
if(this.limit > 7 && this.count < this.limit * 0.25) {
let prime = get(Math.floor(this.limit / 2))
this.resize(prime)
}
return undefined
}
//判空
HashTable.prototype.isEmpty = function(){
return this.count === 0
}
//返回元素个数
HashTable.prototype.size = function(){
return this.count
}
//该变表容量
HashTable.prototype.resize = function(newlimit){
//把旧的数组保存起来
let oldstorage = this.storage
//重置属性
this.storage = []
this.limit = newlimit
//将旧数组里的值按照新的下标存入新的数组
for (let i = 0; i < oldstorage.length; i++) {
let bucket = oldstorage[i]
if(bucket === undefined) continue
for (let j = 0; j < bucket.length; j++) {
let tuple = bucket[j]
this.put(tuple[0],tuple[1])
}
}
}
//判断是否为质数
HashTable.prototype.isPrime = function(num){
//取num的平方根
let temp = parseInt(Math.sqrt(num))
for (let i = 2; i < num; i++) {
if(temp % i === 0){
return false
}
}
return true
}
//转换为质数
HashTable.prototype.getPrime = function(num){
while(!this.isPrime(num)){
num++
}
return num
}
}
JavaSript实现哈希表(链地址法)
最新推荐文章于 2023-06-26 22:22:53 发布