germancin
8/21/2018 - 9:57 AM

Binary Search

Binary Search

function binarySearch(numbers, target){

	// we get the first and the last index from the array.
	let startIndex = 0;
	let endIndex = numbers.length - 1;

	// we check if the target is in the range of the 
	// given array of elements
	if( target < numbers[startIndex] || target > numbers[endIndex]){
		return -1;
	}

	// we create a loop 
	while (1) {

		// we check if hte target is iquals to the 
		// first or the last element of the array of numbers

		if(target === numbers[startIndex] ){
			return startIndex;
		}

		if(target === numbers[endIndex] ){
			return endIndex;
		}

		// if this is true means the indexes got close
		// to one number but still didn't find the number
		// so return false(-1)
		if(endIndex - startIndex <= 1){
			return -1
		}

		// we need to know if the target is smaller
		// than the middle of the array or bigger than
		// the middle index of the array. so we get the middle index
		const middleIndex = Math.floor((startIndex + endIndex) / 2);

		// get the middle number value
		const middleNumber = numbers[middleIndex];

		// now we have to move the indexes so it start looking
		// from the second have of the array (right side)
	        // we move the startIndex to the right side of the array
		// else if the target number is less than the middle number
		// we move the endIndex to the left side of the array.
		// else we return the middle index

		if(target > middleNumber){
			startIndex = middleIndex + 1;
		}else if (target < middleNumber){
			endIndex = middleIndex -1;
		}else {
			return middleIndex;
		}
	}
}

console.log( binarySearch([1,3,6,7,17,13,20], 2) );
console.log( binarySearch([1,3,6,7,17], 17) );