It is often handy to return the index of the found item from a sorted list. The optional second parameter determines if a boolean or index is returned.
Array.prototype.biSearch= function(v, ret){
var L= this.length, i= -1, m;
while(L - i> 1){
if(this[m= L + i>> 1]< v) i= m;
else L= m;
}
if(ret) return this[L]== v? L: -1;
return this[L]== v;
}
Virtually the same code can be used for another common task-adding an item to a sorted array without having to re-sort the whole array.
If the second parameter is not sent, the item will only be inserted if it does not already exist in the array.
Array.prototype.addtoSort= function(v, dup){
var L= this.length, i= -1, m;
while(L - i> 1){
if(this[m= L + i>> 1]< v) i= m;
else L= m;
}
if(this[L]!= v || dup){
return this.splice(L,0,v);
}
return this.length;
}