7

I have an array of sorted ints with a 1,000 or more values (could be up to 5000+). I need to write a function that receives an int and returns a bool based on the element being in the array. I know I can write a for loop with a break, I know I can use jquery .InArray.

What would be the best way to implement this, KNOWING that the array is sorted.

Thanks.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
frenchie
  • 51,731
  • 109
  • 304
  • 510

5 Answers5

10

Knowing that the array is sorted a binary search would be the best approach.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • 1
    http://www.nczonline.net/blog/2009/09/01/computer-science-in-javascript-binary-search/ – Pete Apr 22 '12 at 00:38
10

I think you'd want to use a binary search routine. A binary search routine is enter image description here whereas a linear search is, on average, enter image description here.

There are many variations to choose form. Here's one I found in this article:

function binarySearch(items, value){

    var startIndex  = 0,
        stopIndex   = items.length - 1,
        middle      = Math.floor((stopIndex + startIndex)/2);

    while(items[middle] != value && startIndex < stopIndex){

        //adjust search area
        if (value < items[middle]){
            stopIndex = middle - 1;
        } else if (value > items[middle]){
            startIndex = middle + 1;
        }

        //recalculate middle
        middle = Math.floor((stopIndex + startIndex)/2);
    }

    //make sure it's the right value
    return (items[middle] != value) ? -1 : middle;
}

Or this simpler looking version from this article that has a binary search function in a zillion different languages.

function binary_search_iterative(a, value) {
    var lo = 0, hi = a.length - 1, mid;
    while (lo <= hi) {
        mid = Math.floor((lo+hi)/2);
        if (a[mid] > value)
            hi = mid - 1;
        else if (a[mid] < value)
            lo = mid + 1;
        else
            return mid;
    }
    return null;
}

There's also a binary search in Google closure with the code here.

And, a good description of how the binary search algorithm works on Wikipedia.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
3

If the array's sorted, then the answer's sorted - use a binary chop.

Martin James
  • 24,453
  • 3
  • 36
  • 60
0

If doing lookups more than once, migrate to a map-like object.

var fastLookup = {};
mySortedArray.forEach(function(i){fastLookup[i]=true)});

//Each time:
  if (fastLookup[key]===true){ //do thing
  }
user1212212
  • 1,311
  • 10
  • 6
-2

Many languages already have this implemented for example in java you can just use CollectionsCollections.binarySearch(List> list, T key) method and I'm pretty sure C# also has some sort of BinarySearch method.

Merf
  • 1