Naïve pattern searching is the simplest method among other pattern searching algorithms. It checks for all character of the main string to the pattern. This algorithm is helpful for smaller texts. It does not need any pre-processing phases. We can find substring by checking once for the string. It also does not occupy extra space to perform the operation.
The time complexity of Naïve Pattern Search method is O(m*n). The m is the size of pattern and n is the size of the main string.
Input and Output
Input: Main String: “ABAAABCDBBABCDDEBCABC”, pattern: “ABC” Output: Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18
Algorithm
naivePatternSearch(pattern, text)
Input: The text and the pattern
Output: location, where patterns are present in the text
Begin patLen := pattern Size strLen := string size for i := 0 to (strLen - patLen), do for j := 0 to patLen, do if text[i+j] ≠ pattern[j], then break the loop done if j == patLen, then display the position i, as there pattern found done End
Source Code (C++)
#include<iostream> using namespace std; void naivePatternSearch(string mainString, string pattern, int array[], int *index) { int patLen = pattern.size(); int strLen = mainString.size(); for(int i = 0; i<=(strLen - patLen); i++) { int j; for(j = 0; j<patLen; j++) { //check for each character of pattern if it is matched if(mainString[i+j] != pattern[j]) break; } if(j == patLen) { //the pattern is found (*index)++; array[(*index)] = i; } } } int main() { string mainString = "ABAAABCDBBABCDDEBCABC"; string pattern = "ABC"; int locArray[mainString.size()]; int index = -1; naivePatternSearch(mainString, pattern, locArray, &index); for(int i = 0; i <= index; i++) { cout << "Pattern found at position: " << locArray[i]<<endl; } }
Output
Pattern found at position: 4 Pattern found at position: 10 Pattern found at position: 18
No comments:
Write Comments