Knowledge organisersSearching and sorting algorithms
Understand the main steps of each algorithm, Understand any pre-requisites of an algorithm, Apply the algorithm to a data set, Identify an algorithm if given the code or pseudocode for it
Binary search is an efficient searching algorithm that works only on sorted lists. It repeatedly divides the list in half by comparing the middle element to the target value, then discarding the half that cannot contain the target. This divide-and-conquer approach makes it much faster than linear search for large datasets.
def binary_search(data, target):
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 # Not found
numbers = [4, 7, 8, 11, 15, 18, 20]
print(binary_search(numbers, 8)) # Output: 2