Optimized Naive Algorithm for Pattern Searching | A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; If pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Slide the pattern by j ; Driver code
function search ( pat , txt ) { let M = pat . length ; let N = txt . length ; let i = 0 ; while ( i <= N - M ) { let j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { document . write ( " " + i + " " ) ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } let txt = " " ; let pat = " " ; search ( pat , txt ) ;