Binary search explained:

Praveen David Mathew
3 min readApr 14, 2022

Binary search is one of the highly efficient search algorithm with a complexity of log(n) as here we divide the target array to half n/2 each time till we get the target item , so for an array of size 8 . we get the element with in 3 operation.

Note that binary search can be carried out only for a sorted array so it wont be always the best algorithm to use.

For example , you have an unsorted array of unique element, to find a specific item using binary search , we first need to sort it. The best sorting algorithm complexity is O(nlogn) , after sorting we do binary search. This result in final complexity of nlogn + logn , and as nlogn is the higher term we drop logn , so final Big O is O(nlogn).

Instead if we just checked each element using a for loop , the complexity would have been just O(n) which was much better than O(nlogn).:

https://dev.to/lofiandcode/an-introduction-to-big-o-notation-210o

So how binary search works:

Assume we have an array sorted in ascending order:

[1,2,3,4,5,6,7,8]

Now we have to find index of ‘5’

Step 1:
so what we do is , first check the midIndex in the array for the element.

--

--

Praveen David Mathew

An open source advocator/WebdriverIO Projectcommiter/Postman Supernova/Postman-html-extra contributor/Stack overflow sqa moderator/Speaker