演算法練習--二分搜尋雜湊表-JS 實現,-js

來源:互聯網
上載者:User

演算法練習--二分搜尋雜湊表-JS 實現,-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"));


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.