Python Write a Program to Implement Binary Search
Binary search is an efficient search algorithm suitable for sorted arrays. It repeatedly halves the array to narrow the search range until the target element is found or determined not to exist.
Example
def
binary_search
(
arr
,
target
)
:
low
=
0
high
=
len
(
arr
)
1
while
low
<=
high:
mid
=
(
low + high
)
//
2
if
arr
[
mid
]
==
target:
return
mid
elif
arr
[
mid
]
<
target:
low
=
mid +
1
else
:
high
=
mid -
1
return
1
Example array
arr
=
[
1
,
3
,
5
,
7
,
9
,
11
,
13
,
15
]
target
=
7
Call the binary search function
result
=
binary_search
(
arr
,
target
)
if
result
!=
1
:
(
f
"The element {target} is at index {result} in the array"
)
else
:
(
f
"The element {target} is not in the array"
)
Code analysis:
binary_searchThe function accepts two parameters:arris the sorted array,targetis the target element to find.lowandhighrespectively represent the lowest and highest indices of the current search range.whileThe loop continues whilelowLess than or equal tohigh, indicating the search range is still valid.midCompute the middle index of the current search range.- If both the
arr[mid]Equaltarget, returnmid, indicating the target element is found. - If both the
arr[mid]Less thantarget, then adjustlowismid + 1, indicating the target element is in the right half. - If both the
arr[mid]Greater thantarget, then adjusthighismid - 1, indicating the target element is in the left half. - If the target element is still not found when the loop ends, return
-1, indicating the target element is not in the array.
Output result:
元素 7 在数组中的索引是 3
Python3 Examples