Description
This search basically searches through the array by starting from the middle, checking if the value is > or < than middle. Henceforth make a new middle in that range — Repeat this processHere’s a step-by-step description of using binary search to play the guessing game:
- Let min = 1, and max = n.
- Guess the average of max and min, rounded down so that it is an integer.
- If you guessed the number, stop. You found it!
- If the guess was too low, set min to be one larger than the guess.
- If the guess was too high, set max to be one smaller than the guess.
- Go back to step two.
Visual Representation
%%đź–‹ Edit in Excalidraw, and the dark exported image%%
Javascript:
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while( min <= max ){
guess = Math.floor((min + max)/2) ;
if( array[guess] === targetValue){ return guess; }
else if( array[guess] < targetValue ){ min = guess + 1; }
else{ max = guess - 1;}
}
return -1;
};