DEV Community

Discussion on: Understanding the binary search algorithm

Collapse
 
dim0147 profile image
Bon

So this algorithm can be used with the sorted array only? What happens if the array is [3, 31, 2, 23, 1, 40]

Collapse
 
kibebr profile image
Vitor Leal

Hey, hi! Yes, you can only use this algorithm if the array is sorted.

I'll explain using your array as an example:

Say you have [3, 31, 2, 23, 1, 40], and you're trying to find the number 31. Say, too, that the mid-point is 2 (or even 23, in this case).

In its very first step, the algorithm would ignore everything that's to left of 2, since 31 is higher than 2.

That means that we would end up with:

[2, 23, 1, 40].

Now, it's impossible to find 31.