• 算法练习--二分搜索哈希表-JS 实现


    1. 以哈希KEY的值建立二叉哈希表

    2. 依据传入的哈希值使用二分法搜索


    详细实现例如以下:


    function binarySearchTable(comp){
    this.comp = comp;
    this.kv = new Array();
    }
    
    binarySearchTable.prototype.add = function(k,v){
    if(this.kv.length == 0 || this.comp(this.kv[0].key,k) >= 0){
    
    this.kv.splice(0,0,{key:k,value:v});
    return this;
    }
    else if(this.comp(this.kv[this.kv.length - 1].key,k) <= 0){
    this.kv.push({key:k,value:v});
    return this;
    }
    else{
    for(var i = 1,j = i+1;j < this.kv.length; i ++, j++){
    if((this.comp(this.kv[i].key) < 0 || this.comp(this.kv[i].key) == 0) && 
    (this.comp(this.kv[j].key) > 0 || this.comp(this.kv[j].key) == 0)){
    this.kv.splice(i,0,new {key:k,value:v});
    return this;
    }
    
    }
    }
    
    };
    
    binarySearchTable.prototype.getIndexByKey = function(k){
    var lo = 0;
    var hi = this.kv.length - 1;
    var mid = (lo + hi) / 2 | 0;
    var c = 0;
    while(lo < hi && (++c) < 10){
    
    if(this.comp(k,this.kv[mid].key) == 0){return mid;}
    else if(this.comp(k,this.kv[lo].key) == 0){return lo;}
    else if(this.comp(k,this.kv[hi].key) == 0){return hi;}
    else if(this.comp(this.kv[mid].key,k) < 0){lo = mid;mid = (hi+lo) / 2 | 0;}
    else {hi=mid;mid = (lo+hi)/2 | 0;}
    }
    
    return null;
    };
    
    binarySearchTable.prototype.removeByKey = function(k){
    var index = this.getIndexByKey(k);
    if(index != null){this.kv.splice(index,1);}
    }
    
    var comp = function(k1,k2){return k1 < k2 ? -1 : k1 == k2 ? 0 : 1;};
    var tbl = new binarySearchTable(comp);
    tbl.add("bec",1);
    tbl.add("acd",1);
    tbl.add("abc",1);
    tbl.add("dec",1);
    console.log(tbl.getIndexByKey("abc"));
    
    tbl.removeByKey("abc");
    console.log(tbl.getIndexByKey("abc"));


  • 相关阅读:
    Nginx核心配置-作为上传服务器配置
    Nginx核心配置-作为下载服务器配置
    Nginx核心配置-长连接配置
    Nginx核心配置-检测文件是否存在
    Nginx核心配置-自定义日志路径及清空日志注意事项
    Nginx核心配置-自定义错误页面
    Nginx核心配置-location的登录账户认证实战篇
    Nginx核心配置-location的匹配案例实战篇
    前后端分离-Restful最佳实践
    Django模板技术
  • 原文地址:https://www.cnblogs.com/llguanli/p/7203706.html
Copyright © 2020-2023  润新知