admin管理员组文章数量:1356716
I have an ordered list of integers, and would like to search through them.
What is the fastest way to do this?
Is this the fastest it will work? Or can we optimise it because it is ordered?
Array.prototype.Contains = function(value) {
for (var index = 0; index < this.length; index++) {
if (value == this[index]) {
return true;
}
}
return false;
}
Thanks
I have an ordered list of integers, and would like to search through them.
What is the fastest way to do this?
Is this the fastest it will work? Or can we optimise it because it is ordered?
Array.prototype.Contains = function(value) {
for (var index = 0; index < this.length; index++) {
if (value == this[index]) {
return true;
}
}
return false;
}
Thanks
Share Improve this question asked Dec 3, 2009 at 1:18 RussellRussell 17.7k24 gold badges83 silver badges127 bronze badges 1- 2 This is not a duplicate, as I am specifically asking about an ordered list. – Russell Commented Dec 3, 2009 at 1:26
3 Answers
Reset to default 7Tried implementing a "binary search":
Array.prototype.binarySearch = function(v) {
/* ARRAY MUST BE SORTED */
if ( !this.length ) { return false; }
if ( this[0] === v ) { return true; }
var i, mid,
start = 0,
end = this.length,
c = false;
while ( c = (i = this[mid = start+((end-start)>>1)]) !== v ) {
i < v ? (start = mid) : (end = mid);
if (start >= end - 1) { break; }
}
return !c;
};
If the list is sorted, the fastest way is always a binary search. This is true in all languages, as long as you have an ordered list.
http://en.wikipedia/wiki/Binary_search_algorithm
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 mon 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;
}
本文标签: arraysWhat is the best way to search for an item in a sorted list in javascriptStack Overflow
版权声明:本文标题:arrays - What is the best way to search for an item in a sorted list in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744064602a2584755.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论