## CSDN博客

### 一个排序的Map

//列表节点
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.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];
}
}
}

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