Analysis of binary search

                                                      Binary Search

Binary search is an efficient algorithm for finding an item in a sorted list or array. It works by repeatedly dividing the search interval in half. It follows dictionary opening order

How It Works

  1. Compare the target value to the middle element of the array
  2. If the target equals the middle element, return its position
  3. If the target is less than the middle element, search the left half
  4. If the target is greater than the middle element, search the right half
  5. Repeat until the element is found or the interval is empty

Time Complexity

O(log n) - Much faster than linear search (O(n)) for large datasets

Space Complexity

O(1) for iterative implementation

O(log n) for recursive implementation (due to call stack)

Step-by-Step Execution with  Example

Searching for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]:

First iteration:

Left=0, Right=9

Mid=(0+9)//2=4

data[4]=16 < 23 → search right (Left=5) middle element as per position 16 but we are searching for element 23

Second iteration:

Left=5, Right=9

Mid=(5+9)//2=7

data[7]=56 > 23 → search left (Right=6)
56 is greater than 23 so, our search goes to left

Third iteration:

Left=5, Right=6

Mid=(5+6)//2=5

data[5]=23 == target → return 5

The algorithm found the required number in 3 steps (O(log n) time complexity) instead of potentially 10 in a linear search.

Key Points:

  1. Requires sorted data
  2. All elements must be unique (or you need additional logic for duplicates)
  3. Very efficient with O(log n) time complexity
  4. Space complexity is O(1) as it uses constant extra space

Comments

Popular posts from this blog

Analysis of algorithms viva questions / Interview questions - set1 /sorting algorithms

Operating System Viva questions/interview questions 2025

Recommendation System viva questions/ Interview questions