Python Linear Search

Document 对象参考手册Python3 Examples

Linear search refers to checking each element in an array in a certain order until the specific value to be found 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("Element is not in the array") else: print("The index of the element in the array is", result)

Executing the above code produces the following output:

元素在数组中的索引为 3

Document 对象参考手册Python3 Examples

Other Extensions