Skip to content
Related Articles

Related Articles

Complexity Analysis of Binary Search

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 14 Sep, 2022
View Discussion
Improve Article
Save Article

How does Binary Search work?

This is used to search a sorted array by repeatedly dividing the search interval in half. 

Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the left half. Otherwise, narrow it to the right half. Repeatedly check until the value is found or the interval is empty. 

Complete Interview Preparation - GFG

Examples: 

Input: arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, target = 23

Below is the step-by-step procedure to find the given target element using binary search:

Iteration 1: 

Array: 2, 5, 8, 12, 16, 23, 38, 56, 72, 91

  • Select the middle element. (here 16)
  • Since 23 is greater than 16, so we divide the array into two halves and consider the sub-array after element 16.
  • Now this subarray with the elements after 16 will be taken into the next iteration.

Iteration 2: 

Array: 23, 38, 56, 72, 91

  • Select the middle element. (now 56)
  • Since 23 is smaller than 56, so we divide the array into two halves and consider the sub-array before element 56.
  • Now this subarray with the elements before 56 will be taken into next iteration.

Iteration 3: 

Array: 23, 38

  • Select the middle element. (now 23)
  • Since 23 is the middle element. So the iterations will now stop.
  • Let’s say the iteration in Binary Search terminates after k iterations. In the above example, it terminates after 3 iterations, so here k = 3
  • At each iteration, the array is divided by half. So let’s say the length of the array at any iteration is n

Analysis of input size at each iteration of Binary Search:

At Iteration 1:

Length of array = n

At Iteration 2:

Length of array = n/2

At Iteration 3:

Length of array = (n/2)/2 = n/22

Therefore, after Iteration k:

Length of array = n/2k

Also, we know that after k iterations, the length of the array becomes 1 Therefore, the Length of the array 
n/2k = 1
=> n = 2k
Applying log function on both sides: 

=> log2n = log22k

=> log2n = k * log22

As (loga (a) = 1) Therefore, k = log2(n)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!