Why complexity of Binary Search is O(log n)?

Technology CommunityCategory: SearchingWhy complexity of Binary Search is O(log n)?
VietMX Staff asked 3 years ago

When you do one operation in binary search we reduce the size of the problem by half. To answer the questions we have to answer, how many times can you divide N by 2 until you have 1? This is essentially saying, do a binary search (half the elements) until you found it. In a formula this would be this:

1 = N / 2x

multiply by 2x:

2x = N

now do the log2:

log2(2x)    = log2 N
log2(2) = log2 N
1         = log2 N

this means you can divide log N times until you have everything divided. Which means you have to divide log N (“do the binary search step”) until you found your element.

The same concept explained graphically:

 

binary-search-complexity