Binary Search Algorithm With JavaScript

Serra Saracoglu
2 min readNov 8, 2020

--

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!

From geeks for geeks

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;

}

Binary search works on sorted arrays. Binary search begins by comparing an element in the middle of the array with the target value. If the target value matches the element, its position in the array is returned. If the target value is less than the element, the search continues in the lower half of the array. If the target value is greater than the element, the search continues in the upper half of the array. By doing this, the algorithm eliminates the half in which the target value cannot lie in each iteration.

tip: LEss →LEft

moRe →Right

Here we have code for JavaScript you can try by yourself with other languages as well.

Have fun!

--

--

Serra Saracoglu
Serra Saracoglu

No responses yet