Binary Search Algorithm With JavaScript
First of all before everything we should understand what” Binary Search” is. As we all understand from the name we will search something and it is going to be with famous Divide and Conquer approach.
arr []={1,2,4,5,6,7}
x= 5
We found it!
First Step: We should define our middle index
Second Step: After that if the number which we searching is less than our middle number we should start to investigate our left subarray, if not we will check right partof our array by doing this we will get our target number eventually.
We could have recursive and iterative approach to find to solution.
First of all we need to have start and end points then while start index is less or equal than end index
we should define the middle point of our array to compare our values.
function binary_Search(arr, value){
let firstIndex = 0;
let lastIndex = arr.length — 1;
let middleIndex = Math.floor((lastIndex + firstIndex)/2); while(items[middleIndex] != value && firstIndex < lastIndex) {
if (value < items[middleIndex]) {
lastIndex = middleIndex — 1; — -we are cahnging our end points here
} else if (value > items[middleIndex]) {
firstIndex = middleIndex + 1;
}
middleIndex = Math.floor((lastIndex + firstIndex)/2);
}
return (items[middleIndex] != value) ? -1 : middleIndex;
}
tip: LEss →LEft
moRe →Right
Here we have code for JavaScript you can try by yourself with other languages as well.
Have fun!