dangerChihuahua007
dangerChihuahua007

Reputation: 20895

Why is my javascript binary search erring?

I wrote a binary search in javascript.

Array.prototype.binarySearch = function(find) {
  var low = 0, high = this.length - 1,
      i;
  while (low <= high) {
    i = Math.floor((low + high) / 2);
    if (this[i] > find) { low = i; continue; };
    if (this[i] < find) { high = i; continue; };
    return i;
  }
  return null;
}

It fails though to find 5 in my array of integers.

var intArray = [1, 2, 3, 5]

if (intArray.binarySearch(5))
  alert("found!");
else 
  alert("no found!");

Here is a Fiddle. http://jsfiddle.net/3uPUF/3/

Upvotes: 0

Views: 256

Answers (2)

Hunter McMillen
Hunter McMillen

Reputation: 61512

You have the logic backward for changing low and high, if this[i] > find then you want to look between 1 and i-1. If this[i] < find then you want to look between i+1 and the length of the array.

Try making these changes:

Array.prototype.binarySearch = function(find) {
  var low = 0, high = this.length - 1,
      i;
  while (low <= high) {
    i = Math.floor((low + high) / 2);
    if (this[i] == find) { return i; }; 
    if (this[i] > find)  { high = i - 1;};
    if (this[i] < find)  { low = i + 1;};
  }
  return null;
}

var intArray = [1, 2, 3, 5]
//index of the element in the array or null if not found    
alert(intArray.binarySearch(5));

Upvotes: 6

Jacob
Jacob

Reputation: 78850

Your comparisons are backwards. If the item that is found at i is greater than what you're looking for, then you want to adjust high, not low. See my updated jsFiddle.

Upvotes: 3

Related Questions