Binary Search in Python

Binary Search in Python

Binary Search:

The concept of binary search is like finding a word in a dictionary. Imagine you're looking for a particular word, and the dictionary is sorted alphabetically.

  1. Initial Guess: You open the dictionary roughly in the middle and check the word.

  2. Eliminate Half: If the word you're looking for comes after the word in the middle, you can ignore the first half of the dictionary. If it comes before, you can ignore the second half.

  3. Repeat: You keep repeating this process, halving the remaining possibilities each time. Eventually, you narrow it down to the exact location of the word.

Binary search is efficient because, with each step, you eliminate half of the remaining options. It's like asking, "Is the word I'm looking for before or after this page?" This way, you quickly zoom in on the right section until you find the word. The key is that the list (or dictionary) must be sorted for binary search to work effectively.

Big O notation:

The time complexity (Big O notation) of binary search is O(log n), where 'n' is the number of elements in the sorted array.

In binary search, the key idea is that with each comparison, you are eliminating half of the remaining elements. This logarithmic behavior results in an efficient time complexity of O(log n). This is much faster than linear search (O(n)), where you would have to check each element one by one.

To break it down further:

  • In the first comparison, you have n elements.

  • In the second comparison, you have n/2 elements.

  • In the third comparison, you have n/4 elements.

  • This process continues, and after k comparisons, you have n/(2^k) elements.

When n/(2^k) becomes 1 (reduces to a single element), you've found your element. Solving for k gives you k = log2(n), which is why the time complexity is O(log n).

Code:

# Original array
arr = [1, 32, 5, 107, 56, 87]

# Sorting the array in ascending order
arr.sort()

# Binary search function to find the key in the sorted array
def binary_search(key, start, end, arr):
    # Calculate the middle index of the current search range
    middle = (start + end) // 2

    # Base case: If the search range is invalid, return False
    if start > end:
        return False

    # Check if the key is equal to the middle element
    if key == arr[middle]:
        return True

    # Update the search range based on whether the key is less than or greater than the middle element
    start, end = (start, middle - 1) if key < arr[middle] else (middle + 1, end)

    # Recursive call to binary_search with the updated search range
    return binary_search(key, start, end, arr)

# Call the binary_search function with key=56 and the initial search range (0 to len(arr)-1)
result = binary_search(56, 0, len(arr) - 1, arr)

# Print the result of the binary search
print(result)

Code Explanation:

This code performs a binary search on a sorted list of numbers to check if a specific number (in this case, 56) is present in the list. Here's a breakdown in simpler terms:

  1. Original List: The code starts with an original list of numbers [1, 32, 5, 107, 56, 87].

  2. Sorting: The list is sorted in ascending order to make it easier to perform a binary search.

  3. Binary Search Function: There's a function called binary_search that takes four parameters - the number to search (key), the start and end indices of the current search range, and the sorted list (arr).

  4. Base Case: If the start index becomes greater than the end index during the search, it means the number is not present in the current search range, so it returns False.

  5. Middle Element Check: It checks if the middle element of the current search range is equal to the number we're looking for. If yes, it returns True.

  6. Update Search Range: If the key is less than the middle element, it narrows down the search range to the left half; otherwise, it narrows it down to the right half.

  7. Recursive Call: The function then calls itself recursively with the updated search range.

  8. Result Printing: Finally, it calls the binary_search function with the initial search range and prints the result, which is True if the number (56) is found, and False otherwise.

So, in simple terms, this code is checking if the number 56 is present in the sorted list using a binary search algorithm. If it's present, the result will be True; otherwise, it will be False.