AI Big-O Analyzer | Python

Binary Search Algorithm Efficiency

Analysis of time and space complexities of the binary search algorithm, showcasing its logarithmic time complexity and constant space complexity. Illustration of average-case scenario for better understanding.


Empty image or helper icon

Prompt

def binary_search(arr, x):
    low = 0
    high = len(arr) - 1
    mid = 0
 
    while low <= high:
 
        mid = (high + low) // 2
 
        if arr[mid] < x:
            low = mid + 1
 
        elif arr[mid] > x:
            high = mid - 1
 
        else:
            return mid
 
    return -1

arr = [2, 3, 4, 10, 40]
x = 10

result = binary_search(arr, x)
print(result)

Answer

Code Inspection

The provided code snippet implements the binary search algorithm to find the index of a given element in a sorted array.

Complexity Analysis

  • Time Complexity:

    • Best Case: O(1) - When the element to be found is at the middle index in the first comparison.
    • Worst Case: O(log n) - When the element is not present in the array and all elements need to be considered.
    • Average Case: O(log n) - Considering the element has an equal probability of being in any part of the array.
  • Space Complexity:

    • The algorithm has a space complexity of O(1) as it uses a constant amount of extra space regardless of the size of the input array.
  • Comments:

    • The while loop executes log n times, making the time complexity logarithmic.
    • The algorithm efficiently halves the search space in each iteration, leading to the logarithmic time complexity.

Average-Case Scenario Illustration

For an array of size 1000, where the target element is located in the middle of the array, the binary search algorithm would exhibit average-case behavior. In this scenario, the algorithm would take approximately log₂(1000) = 10 iterations to find the element. Therefore, the expected runtime complexity in this typical scenario would be O(log n). The space complexity remains constant at O(1).

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

Analysis of time and space complexities of the binary search algorithm, showcasing its logarithmic time complexity and constant space complexity. Illustration of average-case scenario for better understanding.