Binary Search

by Paco86

JavaScript

function binarySearch(arr, item){
	var minIndex = 0;
  var maxIndex = arr.length - 1;
  
  while(minIndex <= maxIndex){
  
  	var midIndex = Math.floor((minIndex + maxIndex)/2);
    
    if(arr[midIndex] === item){
    	return midIndex
    }else if(arr[midIndex] < item){
      minIndex = midIndex + 1;
    }else{
      maxIndex = midIndex - 1;
    }
  }
  
  return -1;
}

var arr = [1, 4, 9, 11];

alert(binarySearch(arr, 11));