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

Python Linear Search

Python Linear Search

Document Object Reference Manual Python3 Examples

Linear search means checking each element in an array in order until the specific value being searched for is found.

Example

def

search

(

arr

,

n

,

x

)

:

for

i

in

range

(

0

,

n

)

:

if

(

arr

[

i

]

==

x

)

:

return

i

return

1

Search for character D in array arr

arr

=

[

'

A

'

,

'

B

'

,

'

C

'

,

'

D

'

,

'

E

'

]

x

=

'

D

'

n

=

len

(

arr

)

result

=

search

(

arr

,

n

,

x

)

if

(

result

== -

1

)

:

print

(

"

The element is not in the array

"

)

else

:

print

(

"

The index of the element in the array is

"

,

result

)

The output of the code above is:


元素在数组中的索引为 3

Document Object Reference Manual Python3 Examples