Binary search: Difference between revisions
Appearance
Create binary search page |
Add syntax highlighting to code example |
||
| Line 3: | Line 3: | ||
Example in Python: | Example in Python: | ||
<syntaxhighlight lang="python3" line="1"> | |||
def binary_search(array, target): | |||
min = 0 | |||
max = len(array) | |||
while min <= max: | |||
mid = (min + max) // 2 | |||
if array[mid] < target: | |||
min = mid + 1 | |||
elif array[mid] > target: | |||
max = mid - 1 | |||
else: | |||
return mid | |||
# Not found | |||
return -1 | |||
</syntaxhighlight> | |||
Revision as of 11:08, 4 January 2026
Binary search is a search algorithm to find a value in a sorted array. It works by starting at the middle of the array and checking if the target value is higher or lower than the middle value. If it is lower, the algorithm then treats the bottom half as the new array and repeats the process of checking the middle value until the target value is found. If the target is higher than the midpoint, the top half of the array is used.
Example in Python:
def binary_search(array, target):
min = 0
max = len(array)
while min <= max:
mid = (min + max) // 2
if array[mid] < target:
min = mid + 1
elif array[mid] > target:
max = mid - 1
else:
return mid
# Not found
return -1