Binary Search

Kulani Baloyi / May 21, 2024

3 min read

Discover what binary search is and the beauty that lies in its unique application


Binary Search employs the divide-and-conquer approach to locate a target element within a sorted list with lightning speed. Here's the gist:

  1. Start with the entire list.
  2. Calculate the first,last and middle(approximate) index.
  3. Compare the target element with the element at these indexs.
  4. If any are equal, you've found your target!
  5. If the target is less than middle index, discard the right half of the list and repeat steps 1-3 on the left half.
  6. If the target is greater, discard the left half of the list and repeat steps 1-3 on the right half.

Why Binary Search Shines

The beauty of Binary Search lies in its ability to eliminate half of the remaining elements with each comparison. This significantly reduces the search space, making it incredibly efficient for large sorted datasets.

def binary_search(data, target):
  # data will be a list of whole numbers
  low = 0
  high = len(data) - 1
 
  while low <= high:
    mid = (low + high) // 2
    if data[mid] == target:
      return mid
    elif data[mid] < target:
      low = mid + 1
    else:
      high = mid - 1
 
  return -1  # Target element not found
 
# Example usage
sorted_data = [1, 3, 5, 7, 9]
target = 7
index = binary_search(sorted_data, target)
 
if index != -1:
  print(f"Target element {target} found at index {index}")
else:
  print(f"Target element {target} not found in the list")
 

This code implements the binary_search function that iteratively searches the sorted list using the divide-and-conquer strategy.

Real-World Applications of Binary Search

Binary Search finds its way into various applications:

Search Engines: Locating specific keywords within massive document databases.

Spell Checkers: Identifying misspelled words by comparing them to a dictionary.

Data Analysis: Finding specific data points within large datasets.

Limitations and Considerations

Sorted Data: Binary Search only works on sorted lists. Unsorted lists require sorting before applying Binary Search, which might negate its efficiency advantage for small datasets.

Worst Case: In the worst case (target not present or the list is empty), Binary Search performs the same number of comparisons as a linear search (iterating through all elements).

Related articles:

Dijktras Algorithm
Jul 15, 2024
Depth First Sort
Jul 12, 2024
Orders of growth
Jul 3, 2024
Bubble Sort
May 22, 2024
Insertion Sort
May 21, 2024