Binary Search in python made easy
2 min readFeb 11, 2023
Think of the binary search algorithm as searching for a specific book in a library. You start in the middle of the shelves and determine if the book you’re looking for is on the left or right side of the shelves. Then you move to that side of the shelves and repeat the process until you find the book or determine that it’s not in the library.
Here’s an implementation of the binary search algorithm in Python:
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Explanation of each line:
- The
binary_search
function takes two arguments,arr
andtarget
.arr
is the list of values to search through, andtarget
is the value you're looking for. left, right = 0, len(arr) - 1
setsleft
to 0 andright
to the index of the last element inarr
. These are the boundaries of the search.while left <= right
is the condition that allows us to keep searching as long as there are still elements to look at.mid = (left + right) // 2
calculates the index of the middle element in the current section of the list.if arr[mid] == target
checks if the value at themid
index is equal to the target. If it is, the function returnsmid
because we've found the target.elif arr[mid] < target
checks if the value at themid
index is less than the target. If it is, the search continues in the right half of the list, soleft
is set tomid + 1
.else
is executed if the value at themid
index is greater than the target. The search continues in the left half of the list, soright
is set tomid - 1
.- If the loop exits, it means the target wasn’t found, so the function returns -1.
Limitations:
- The binary search algorithm only works if the list is sorted. If the list is not sorted, the algorithm won’t return the correct result.
- The binary search algorithm is less efficient than other search algorithms when searching through large lists. For very large lists, it may be faster to use a different search algorithm.
- The binary search algorithm can only be used to search for a value in a list, not to find the index of the first occurrence of a value.
When to use:
- Use the binary search algorithm when searching through a large, sorted list.
- Use the binary search algorithm when searching for a specific value in a list, not the first occurrence of a value.
- Use the binary search algorithm when the list is too large to search through linearly.