zoukankan      html  css  js  c++  java
  • 算法练习--二分搜索哈希表-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"));


  • 相关阅读:
    BZOJ3575 [Hnoi2014]道路堵塞
    BZOJ4456/UOJ184 [Zjoi2016]旅行者
    BZOJ4455/UOJ185 [Zjoi2016]小星星
    BZOJ1036 [ZJOI2008]树的统计Count
    BZOJ2594 [Wc2006]水管局长数据加强版
    BZOJ3669/UOJ3 魔法森林(LCT)
    BZOJ1012:[JSOI2008]最大数
    洛谷【P1175】表达式的转换
    HDU4699:Editor
    BZOJ3039:玉蟾宫
  • 原文地址:https://www.cnblogs.com/llguanli/p/7203706.html
Copyright © 2011-2022 走看看