T = input text P = pattern (that we need to find in the text T) T[i] = the ith character of T P[j] = the jth characetr of P T[i] == P[j] means: check if the ith character of T and the jth characetr of P are equal. 


Observations: (what we learned from the above examples)

while ( not all characters matched ) { if ( T[i] == P[j] ) { /*  Try to match NEXT pair of characters  */ i++; j++; if ( j == P.length ) { P has been found ! (You can quit, or keep going to find another match) } } .... } 



i_{0} = i  j 
Example:

Example:
i = i  j + 1; j = 0; 
$64,000 question:


Example:
i_{0} = i_{0} + 1; // Move pattern P one character further i = i_{0}; // Restart matching at position i_{0} in T j = 0; // Restart matching at position 0 in P 
i = i  j + 1; j = 0; achieves the same rsult as: i_{0} = i_{0} + 1; // Move pattern P one character further i = i_{0}; // Restart matching at position i_{0} in T j = 0; // Restart matching at position 0 in P because: i_{0} is equal to i  j 
Basic( T, P ) { int i0, i, j, m, n; n = T.length(); m = P.length(); i0 = 0; // Line P up with the first character of T i = 0; // Start matching with first char in T j = 0; // Start matching with first char in P while ( i < n ) // Not all characters used { if ( T[i] == P[j] ) { i++; // Match next pair j++; if ( j == m ) return ( i0 ); // Match found at position i0 !!! } else { /* =========================================== P does not start at position i0... Try another position by moving P further =========================================== */ i0 = i0 + 1; // Move pattern P one character further i = i0; // Restart matching at position i0 in T j = 0; // Restart matching at position 0 in P } } return 1; // No match found } 
How to run the program:
