Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sequential Search #25

Open
barretlee opened this issue Jul 10, 2017 · 0 comments
Open

Sequential Search #25

barretlee opened this issue Jul 10, 2017 · 0 comments

Comments

@barretlee
Copy link
Owner

顺序查找(Sequential Search),需要通过链表构建一张深度为 N 的无序符号表。你可以简单地理解它为一个数组,只不过它的每个单元都是一个键值对,并且它的数据结构比数组更加松散,便于我们做插入/删除等操作。

无序符号表的实现,十分简单,可以看这里:

chapters/chapter-3-searching/3.1-elementary-symbol-tables/sequentialSearchST.js

function sequentialSearchST() {

  function Node(key, val, next) {
    this.key = key;
    this.val = val;
    this.next = next;
  }

  var first = null;

  return {
    links: null,
    insertWhere: function(node, where) {
      var n = new Node(node.key, node.val);
      var l = this.links;
      if(where) {
        while(l) {
          if (l.key == where.key || l.val == where.val) {
            var ll = l.next;
            l.next = n;
            n.next = ll;
            break;
          }
          l = l.next;
        }
      } else {
        n.next = l;
        this.links = n;
      }
      return null;
    },
    findWhere: function(where) {
      var l = this.links;
      var depth = 0;
      while(l) {
        if(l.key == where.key || l.val == where.val) {
          var output = { depth: depth };
          for(var key  in l) if(key !== 'next') output[key] = l[key];
          return output;
        }
        depth++;
        l = l.next;
      }
      return -1;
    }
  }
}

一个长度为 N 的无序链表,每次查询和删除操作,最多需要 N 次,也就是说,我们构建一个长度为 N 的不重复无序链表,最多需要 ~N2 / 2 次比较。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant