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:
Identify the middle element within this interval.
Comparison:
Compare the target value with the middle element:
Iteration:
Continue dividing the interval in half and comparing until the target value is found or the interval becomes empty.
Result:
Illustrative Example:
Let's find the number 35
in the sorted list: [5, 12, 20, 35, 48, 60, 72]
.
[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:
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 →