• 算法练习--二分搜索哈希表-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"));


  • 相关阅读:
    电脑休眠真是神一样
    用visual studio 2017来调试python
    判断两个字符串是不是异位词
    算法题思路总结和leecode继续历程
    今日头条笔试题目,还是没过.效率不够
    The init method
    Object-oriented features
    Modifiers
    Pure functions
    Classes and functions
  • 原文地址:https://www.cnblogs.com/llguanli/p/7203706.html
Copyright © 2020-2023  润新知