The naive algorithm checks for the equivalence of pattern P with the substring of the text T[s:s+m-1] starting with the shift s = 0 and going all the way to s = n-m.
Performance The best case occurs when the substring with shift = 0 matches the pattern giving a time complexity of O(m). The worst case occurs when the pattern matches all but the last character of the m-substring produced by each of the shift. In this case, the time complexity is O((n-m)m). In the average case, the expected succesful consecutive character matches while comparing a random pattern with a random m-substring is given by: Summation of [(1/len(Σ))^k * (len(Σ)-1)/len(Σ)] * (k+1) from k = 0 to m where the quantity in [] is the probability of having k successful matches followed by one unsuccesful match. For english alphabet, the summation is close to 1. Hence, in average case the time complexity is O(n-m).
Proof of Correctness Supposing that T[s, s+m-1] = P, the match will be detected in the sth iteration of the loop. If however a match doesn't exist, the test will fail in each of the iteration and a no-match-found identifier will be returned.
35 int n = text.length(), m = pattern.length();
36 for(s = 0; s <= n - m; s++)
39 if(text.substr(s, m) == pattern)
42 return std::string::npos;