Linear Searching

    0

    1

    Mahendra Kumar

    intermediateDSAlogic•••

    Python Program for Linear Search

    ALGORITHM: The procedure to find an element in a given array or list through linear search, a) Take an array and the search key. Assume they are:- array and key b) Traverse through the array. c) Compare the key with each element. d) If the match is found then return the position. e) Else repeat the process until the end of the array. f) After traversing the array If the match is not found then return -1.

    def linearSearch(arr, key):  #user-defined function
        for i in range(len(arr)): 
            if (arr[i] == key): 
                return i 
        return -1
    arr = [50, 90, 30, 70, 60]  #array
    key = 70  #search key
    index = linearSearch(arr, key) #calling function
    # display result
    if (index == -1):
        print(key, 'not Found.
    else:
        print(key, 'Found at Index', index)
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Explore
    • Cookbooks
    • Playground
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.