...

/

Complexity Analysis

Complexity Analysis

Let's discuss how fast binary search is and how much memory it uses.

We'll cover the following...
Q

What will be the space complexity for binary search in terms of Big O notation?

A)

O(log_2 \space n)

B)

O(2 ^ n)

C)

O(1)

D)

O(n ^ 2)

Q

What will be the time complexity for binary search in terms of Big O notation?

A)

O(log_2 \space n)

B)

O(2 ^ n)

C)

O(n)

D)

O(n ^ 2)

Time complexity

The essential property of binary search is to reduce the search area to, nearly, half of the original size.

Suppose we have n` elements in our search array. On each iteration, we’re down to ​ 2n elements. The search area keeps halving from n to ​2​n, to 4​n, to 8n, and so on, until the area becomes of size 1 (unless we found the target in some previous step).

At this point, we either find the value or prove that it doesn’t exist in the search array.

The total runtime is then a matter of how many steps (dividing n by 2 each time) we can take until n becomes 1.

Here is a visual representation of our algorithm for the worst cases:

  • When the target is the first element in the array:
Step 0:Step 1:Step 2:Step 3:Step 4:111113333555577711111113131717191923232931374143475359
Let's binary search for 1.
  • When the target is the last element in the array:
Step 0:Step 1:Step 2:Step 3:Step 4:135711131719232329293131373741414143434347474747535353535959595959
Let's binary search for 59.

There are 1717 elements in our array. To find the number of times we have ...