Binary search is a highly efficient algorithm for finding a specific value within a sorted list or array. It works by repeatedly dividing the search interval in half. Here’s how it functions:
Initialization: - Start with the entire sorted list as the search interval. - Identify the middle element within this interval.
Comparison: - Compare the target value with the middle element:
Iteration: - Repeat steps 1 and 2 with the new search interval. - Continue dividing the interval in half and comparing until the target value is found or the interval becomes empty.
Result: - If the target value is found, the algorithm returns its index (position). - If the target value is not found, the algorithm returns an indication of its absence (e.g., -1).
Illustrative Example:
Let’s find the number 35 in the sorted list: [5, 12, 20, 35, 48, 60, 72].
Initialization:
- Search interval: [5, 12, 20, 35, 48, 60, 72]
- Middle element: 35
Comparison:
- 35 (target) is equal to 35 (middle element), so the target value is found!
Result:
- The algorithm returns the index of 35, which is 3.
Code Snippet (Conceptual):
function binarySearch(list, target):
low = 0
high = length(list) - 1
while low <= high:
mid = (low + high) // 2
if list[mid] == target:
return mid
elif list[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Advantages of Binary Search:
Limitations:
Applications:
Create a customised learning path powered by AI — stay focused, track progress, and earn certificates.
Build Your Learning Path →