Key Takeaways: Binary Search is an incredibly fast searching algorithm that finds the position of a target value within a sorted array. It works by repeatedly dividing the search space in half, resulting in an O(log n) time complexity.
While sorting arrays is important, we usually sort data so that we can search it efficiently.
If you have an unsorted array, you have to use Linear Search (checking every item one by one). But if your array is sorted, you can use the much faster Binary Search.
Binary Search uses a Divide and Conquer strategy.
Because the array is already sorted, you can compare your target value directly to the middle element of the array:
You then repeat this process on the remaining half until you find the target or run out of elements to check.
Binary Search: Halving the search space with every step to find the target quickly.
Let's search for the target 23 in the following sorted array:
[2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
Step 1:
16.23 > 16, we know 23 must be on the right side.[2, 5, 8, 12, 16].Step 2:
[23, 38, 56, 72, 91].56.23 < 56, we know 23 must be on the left side of this section.[56, 72, 91].Step 3:
[23, 38].23.Here is how you write Binary Search in Python. We use two pointers (left and right) to keep track of the portion of the array we are currently searching.
def binary_search(arr, target): left = 0 right = len(arr) - 1 while left <= right: mid = (left + right) // 2 # Find the middle index # Check if target is present at mid if arr[mid] == target: return mid # If target is greater, ignore left half elif arr[mid] < target: left = mid + 1 # If target is smaller, ignore right half else: right = mid - 1 # Target was not found return -1numbers = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] target = 23 result = binary_search(numbers, target)
if result != -1: print(f"Element {target} found at index {result}") else: print("Element not found in array")
O(log n). Because we cut the array in half every time, the number of steps required grows very slowly. For an array of 1,000,000 items, Binary Search takes at most 20 steps!O(1). It only requires a few variables (left, right, mid) to execute, regardless of how large the array is.What is the most important prerequisite for using Binary Search on an array?