0
0
DSA C++programming~5 mins

Binary Search Recursive Approach in DSA C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Binary Search Recursive Approach
O(log n)
Understanding Time Complexity

We want to understand how the time taken by recursive binary search changes as the input size grows.

Specifically, how many steps does it take to find an element in a sorted list?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int binarySearch(int arr[], int left, int right, int target) {
    if (left > right) return -1;
    int mid = left + (right - left) / 2;
    if (arr[mid] == target) return mid;
    if (arr[mid] > target) return binarySearch(arr, left, mid - 1, target);
    return binarySearch(arr, mid + 1, right, target);
}
    

This code searches for a target value in a sorted array by repeatedly dividing the search range in half.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Recursive call that halves the search range each time.
  • How many times: At most, the function calls itself until the search range is empty, roughly halving the size each time.
How Execution Grows With Input

Each step cuts the search space in half, so the number of steps grows slowly as input size increases.

Input Size (n)Approx. Operations
10About 4 steps
100About 7 steps
1000About 10 steps

Pattern observation: Doubling the input size adds only one extra step.

Final Time Complexity

Time Complexity: O(log n)

This means the number of steps grows slowly, increasing by one each time the input size doubles.

Common Mistake

[X] Wrong: "Binary search checks every element one by one, so it is O(n)."

[OK] Correct: Binary search does not check all elements; it cuts the search space in half each step, so it is much faster than checking one by one.

Interview Connect

Understanding binary search time complexity shows you can analyze efficient algorithms and explain why they work well on large data.

Self-Check

"What if we changed the recursive binary search to an iterative version? How would the time complexity change?"