Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Write a Program to Implement Binary Search

Python Write a Program to Implement Binary Search

Document Object Reference Manual Python3 Examples

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

:

   

print

(

f

"The element {target} is at index {result} in the array"

)

else

:

   

print

(

f

"The element {target} is not in the array"

)

Code analysis:

  1. binary_search The function accepts two parameters:arr is the sorted array,target is the target element to find.
  2. low and high respectively represent the lowest and highest indices of the current search range.
  3. while The loop continues while low Less than or equal to high , indicating the search range is still valid.
  4. mid Compute the middle index of the current search range.
  5. If both the arr[mid] Equal target, return mid, indicating the target element is found.
  6. If both the arr[mid] Less than target, then adjust low is mid + 1, indicating the target element is in the right half.
  7. If both the arr[mid] Greater than target, then adjust high is mid - 1, indicating the target element is in the left half.
  8. 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

Document Object Reference Manual Python3 Examples