Sentinel Linear Search | 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
function sentinelSearch ( arr , n , key ) { var last = arr [ n - 1 ] ; arr [ n - 1 ] = key ; var i = 0 ; while ( arr [ i ] != key ) i ++ ; arr [ n - 1 ] = last ; if ( ( i < n - 1 ) || ( arr [ n - 1 ] == key ) ) document . write ( key + " " + i ) ; else document . write ( " " ) ; } var arr = [ 10 , 20 , 180 , 30 , 60 , 50 , 110 , 100 , 70 ] ; var n = arr . length ; var key = 180 ; sentinelSearch ( arr , n , key ) ;