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

Python Binary Search

Python Binary Search

Document Object Reference Manual Python3 Examples

Binary search is a search algorithm for finding a specific element in a sorted array. The search starts at the middle element; if the middle element is exactly the element being searched for, the search ends; if the target element is greater or smaller than the middle element, the search continues in the half that is greater or smaller, again starting from the middle. If at some step the array is empty, the element is not found. Each comparison halves the search range.

Example : recursive

Return the index of x in arr, or -1 if it does not exist

def

binarySearch

(

arr

,

l

,

r

,

x

)

:

Basic checks

if

r

=

l

:

mid

=

int

(

l

(

r

l

)

/

2

)

The element is exactly at the middle position

if

arr

[

mid

]

==

x

:

return

mid

If the element is less than the middle element, only the left elements need to be compared

elif

arr

[

mid

]

x

:

return

binarySearch

(

arr

,

l

,

mid

1

,

x

)

If the element is greater than the middle element, only the right elements need to be compared

else

:

return

binarySearch

(

arr

,

mid

1

,

r

,

x

)

else

:

Not found

return

1

Test array

arr

=

[

2

,

3

,

4

,

10

,

40

]

x

=

10

Function call

result

=

binarySearch

(

arr

,

0

,

len

(

arr

)

1

,

x

)

if

result

!= -

1

:

print

(

"

The element's index in the array is %d

"

%

result

)

else

:

print

(

"

The element is not in the array

"

)

The output of the code above is:


元素在数组中的索引为 3

Document Object Reference Manual Python3 Examples