最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - What is the best way to search for an item in a sorted list in javascript? - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 7

Tried 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;
}
发布评论

评论列表(0)

  1. 暂无评论