Sentinel Linear Search | Python3 implementation of the approach Function to search key in the given array ; Function to search x in the given array ; Last element of the array ; Element to be searched is placed at the last index ; Put the last element back ; Driver code
def sentinelSearch ( arr , n , key ) : NEW_LINE def sentinelSearch ( arr , n , key ) : NEW_LINE INDENT last = arr [ n - 1 ] NEW_LINE arr [ n - 1 ] = key NEW_LINE i = 0 NEW_LINE while ( arr [ i ] != key ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT arr [ n - 1 ] = last NEW_LINE if ( ( i < n - 1 ) or ( arr [ n - 1 ] == key ) ) : NEW_LINE INDENT print ( key , " is ▁ present ▁ at ▁ index " , i ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element ▁ Not ▁ found " ) NEW_LINE DEDENT DEDENT arr = [ 10 , 20 , 180 , 30 , 60 , 50 , 110 , 100 , 70 ] NEW_LINE n = len ( arr ) NEW_LINE key = 180 NEW_LINE sentinelSearch ( arr , n , key ) NEW_LINE