CSDN博客

img treeroot

一个排序的Map

发表于2004/10/11 21:17:00  1315人阅读

这里就是一个有序的映射,本来应该做一个哈希表,实在对javascript没有什么了解,只能
凑合着用这个了。查找的复杂度为log(n)
//列表节点
function Entry(key,value){
   this.key=key;
   this.value=value;
}

//有序的映射
function SortedMap(capacity,autoIncrease){
   this.capacity=capacity;
   this.autoIncrease=autoIncrease;
   this.size=0;
   this.ensureCapacity =ensureCapacity;
   this.add = add;
   this.search = search;
   this.buffer =new Array(capacity);
   this.getIndex = getIndex;
   this.get=get;
}
function ensureCapacity(){
 if(this.antoCrease && (this.size>=this.array.length)){
  var old = this.buffer;
  this.buffer=new Array((this.buffer.length+1)*2);
  for(var i=0;i<old.length;i++){
   this.buffer[i]=old[i];
  }
 }
}

function add(entry){
 this.ensureCapacity();
 var index = this.getIndex(entry.key);
 
 for(var i=this.size;i>index;){
  this.buffer[i]=this.buffer[--i];
 }

 this.buffer[index]=entry;
 this.size++; 
}
function getIndex(key){
 if(this.size==0) return 0;
 
 var min=0,max=this.size-1;
 var mid=0;
 while(min<=max){
  mid = (min+max) >> 1;
  if(key==this.buffer[mid].key){
   return mid;
  }
  else if(key<this.buffer[mid].key){
      max=mid-1;
  }
  else{
   min=mid+1;
  }
 }
 mid =(min+max) >>1;
 return mid+1;
}
function search(key){
 var min=0,max=this.size-1;
 
 while(min<=max){
  var mid=(min+max)>>1;
  if(key==this.buffer[mid].key){
   return this.buffer[mid].value;
  }
  else if(key<this.buffer[mid].key){
      max=mid-1;
  }
  else{
   min=mid+1;
  }
 }
 return null;
}
function get(index){
 return this.buffer[index];
}

阅读全文
0 0

相关文章推荐

img
取 消
img