js数据结构——符号表 二分查找

符号表

定义: 符号表是一种存储键值对的数据结构, 支持两种操作: 插入(put), 查找(get)。

API

具体API
这里写图片描述
规则
* 每个键只对应于一个值
* 当用例代码向表中存入的键值对和表中已有键冲突,新值取代旧值。

顺序查找(基于无序链表)

效率底下

class Node {
  constructor (key, value, next) {
    this.key = key;
    this.value = value;
    this.next = next;
  }
}
class SequentialSearchST {
  constructor () {
    this.first = null;
  }
  get (key) {
    let temp = this.first;
    while(temp && temp.key !== key) {
      temp = temp.next;
    }
    return temp && temp.value;
  }
  put (key, value){
    let temp = this.first;
    let prev =null;
    while(temp && temp.key !== key){
      prev = temp;
      temp = temp.next;
    }
    if(value !== undefined && temp == null ) {
      this.first = new Node(key, value, this.first);
      return;
    }
    if(value == undefined){
      if(prev === null){
        this.first =this.first && this.first.next;
      } else {
        prev.next = temp && temp.next;
      }
    }else{
      temp.value = value;
    }
  }
}
二分查找(基于有序数组)
class BinarySearchST {
  constructor(){
    this.keys = [];
    this.values = [];
    this.N = 0;
  }
  size () {
    return this.N;
  }
  isEmpty () {
    return this.N === 0;
  }
  get (key) {
    if (this.isEmpty()) return null;
    let i = this.rank(key, 0, this.N-1);
    if (i < this.N && compare(this.keys[i], key) === 0) return this.values[i];
    else return null;   
  }
  put (key, value){
    let i = this.rank(key, 0, this.N-1);
    if (i < this.N && compare(this.keys[i], key) === 0) { 
      this.values[i] = value;
      return ;
    }
    this.keys.splice(i, 0, key);
    this.values.splice(i, 0, value);
    this.N++;
  }
  rank (key, lo, hi) { //如果查找不到,key<this.keys[returnValue],key>this.keys[returnValue - 1];
    if (lo > hi) return lo;
    let mid = Math.floor((lo + hi) / 2);
    let cmp = compare(key, this.keys[mid]);
    if (cmp < 0) {
      return this.rank(key, mid+1, hi);
    } else if (cmp > 0) {
      return this.rank(key, lo, mid-1);
    } else {
      return mid;
    }
  }
}
function compare (key1, key2) {//比较key1,key2的方法,自定义。
  if (key1 < key2) {
    return 1;
  }else if(key1 === key2) {
    return 0;
  }else {
    return -1
  }
}

对N个键的有序数组进行二分查找最多需要(lgN+1)次比较。这里写图片描述

猜你喜欢

转载自blog.csdn.net/lay136362687/article/details/81304037