avatarAsad iqbal

Summary

The provided web content offers a comprehensive guide on implementing binary search in Python, detailing both iterative and recursive methods, and introduces the built-in bisect module for efficient searching within sorted lists.

Abstract

The web content titled "Binary Search in Python" is a detailed tutorial that explains the binary search algorithm, a fundamental and efficient method for locating an element within a sorted dataset. It emphasizes the importance of binary search over linear search, especially for large datasets, and provides practical Python code examples for both iterative and recursive binary search implementations. Additionally, the article highlights the use of Python's bisect module as a fast and easy alternative to custom binary search functions. The tutorial aims to equip Python developers with the knowledge to effectively utilize binary search in their projects.

Opinions

  • The author suggests that binary search is a crucial algorithm for developers due to its efficiency in searching through sorted datasets.
  • The iterative method is described as straightforward and efficient, with a preference for its clarity.
  • The recursive method is presented as an alternative to the iterative approach, offering a different perspective on the binary search algorithm.
  • The bisect module is recommended for its ease of use and performance benefits, eliminating the need for developers to write their own binary search functions.
  • The article encourages readers to engage with the content by clapping for the story and following the author on various platforms for more content.
  • The author promotes their website, DeepNexus, and other learning resources, indicating a commitment to providing educational content in the field of technology and programming.

Binary Search in Python

Master Binary Search in Python: Learn iterative and recursive methods, plus a built-in bisect module for efficient searching.

When you need to find a value in a dataset, your objective is to locate its index or position so that you can access and utilize the value in your code. There are various search algorithms available to assist you in finding the index of a specific value. One of the most efficient and fundamental methods is binary search. A binary search algorithm finds a particular element in the list.✨

Generally, an algorithm is a precise sequence of instructions a computer follows to accomplish a specific task or solve a problem. Check out the blog post, What is an Algorithm, to learn about the many different kinds of algorithms in machine learning.

If you are a free member, continue reading the full article here. Link

source

Concept of Binary Search

We can find the element position in the binary search algorithm using the following methods.

  • Recursive Method: This is like asking a friend to help you find the book. You ask them to look in one half of the library; if they don’t see it, they ask another friend to look in the other half. This keeps happening until the book is found.
  • Iterative Method: This is like searching for the book yourself. You look in one half of the library, then the other half, and keep doing this until you find the book.

Both methods help you find what you’re looking for quickly and efficiently!

Let’s implement binary search in a step-by-step manner.

We have a sorted list of elements and are looking for the index position of 45.

[12, 24, 32, 39, 45, 50, 54]

So, we are setting two pointers in our list. One pointer denotes the smaller value, low, and the second denotes the highest value, high.

Next, we calculate the value of the middle element in the array.

mid = (low+high)/2  

Here, the low is 0, and the high is 7.

mid = (0+7)/2  
mid = 3 (Integer)

Now, we will compare the searched element to the mid-index value. In this case, 32 is not equal to 45, so we need to make further comparisons to find the element.

If the number we are searching is equal to the mid, then return mid; otherwise, move to the next comparison.

The number to be searched is greater than the middle number; we compare the n with the middle element of the elements on the right side of the mid and set low to low = mid + 1.

Otherwise, compare the n with the middle element of the elements on the left side of mid and set high to high = mid -1.

source

Implementing Binary Search in Python

Let’s explore a few ways of implementing a simple binary search in Python. But first, we need to establish a simple dataset to work with and a target value to search for. Imagine we have the following sorted array and search target:

arr = [12, 24, 32, 39, 45, 50, 54]
target = 45

Iterative method

The iterative method is perhaps the most straightforward approach. Using this method, we use a while loop to repeatedly divide the search interval in half until we find our target. This method is often favored for its clarity and efficiency.

def binary_search_iterative(arr, target):
  """
  Performs a binary search iteratively.

  Args:
    arr: A sorted array of numbers.
    target: The number to search for.

  Returns:
    The index of the target if found, otherwise -1.
  """
  low = 0
  high = len(arr) - 1
  while low <= high:
    mid = (low + high) // 2
    if arr[mid] == target:
      return mid
    elif arr[mid] < target:
      low = mid + 1
    else:
      high = mid - 1
  return -1

arr = [12, 24, 32, 39, 45, 50, 54]
target = 45
result = binary_search_iterative(arr, target)
print(f"Target found at index: {result}")

Output:

image by Author

Recursive method

The recursive method for binary search is another way to implement this algorithm. Instead of using a loop, the function calls itself, adjusting the search bounds each time until it finds the target or determines that the target isn’t present.

Here’s how you can implement binary search recursively:

def binary_search_recursive(arr, low, high, target):
  """
  Performs a binary search recursively.

  Args:
    arr: A sorted array of numbers.
    low: The starting index of the search interval.
    high: The ending index of the search interval.
    target: The number to search for.

  Returns:
    The index of the target if found, otherwise -1.
  """
  if high >= low:
    mid = (low + high) // 2
    if arr[mid] == target:
      return mid
    elif arr[mid] > target:
      return binary_search_recursive(arr, low, mid - 1, target)
    else:
      return binary_search_recursive(arr, mid + 1, high, target)
  else:
    return -1

arr = [12, 24, 32, 39, 45, 50, 54]
target = 45
result = binary_search_recursive(arr, 0, len(arr) - 1, target)
print(f"Target found at index: {result}")

Output:

image by Author

Supercharge your search with Python’s bisect module!

Use Python’s bisect module for fast and easy binary search. Say goodbye to building your own function!

# Import the bisect module
import bisect

arr = [12, 24, 32, 39, 45, 50, 54]
target = 45

# Call the module and provide the array and the target value
index = bisect.bisect_left(arr, target)

if index < len(arr) and arr[index] == target:
    print(f"Target found at index: {index}")
else:
    print("Target not found")

Output:

image by Author

Conclusion

Binary search is a powerful and efficient algorithm that every Python developer should have in their toolkit. It provides a significant performance advantage over linear search, especially with large datasets, whether implemented iteratively or recursively.

Further Resources:

Thanks for reading✨ If you like the article, make sure to:

Python
Algorithms
Machine Learning
JavaScript
AI
Recommended from ReadMedium