C Program for Naive algorithm for Pattern Searching


Pattern matching in C− We have to find if a string is present in another string, as an example, the string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e. position it is present at) is displayed. We tend to create a function that receives 2 character arrays and returns the position if matching happens otherwise returns -1.

Input: txt = "HERE IS A NICE CAP"
   pattern = "NICE"
Output: Pattern found at index 10
Input: txt = "XYZXACAADXYZXYZX"
   pattern = "XYZX"
Output: Pattern found at index 0
   Pattern found at index 9
   Pattern found at index 12

We are solving this problem with Naive Pattern Searching. This algorithm is useful for smaller texts. Naive is a simple and inefficient way to see wherever one string occurs within another is to examine every place it could be at, one by one, to examine if it's there.

The time complexity of the Naive Algorithm is O(mn), where m is the size of the pattern to be searched and n is the size of the container string.

Pattern searching is a very crucial problem in computer science. Whenever we seek for a string in notepad/word file or browser or database or in some information, pattern searching algorithms are used to show the search results.

Algorithm

naive_algorithm(pattern, text)

Input − The text and the pattern

Output − locations, where the pattern is present in the text

Start
   pat_len := pattern Size
   str_len := string size
   for i := 0 to (str_len - pat_len), do
      for j := 0 to pat_len, do
         if text[i+j] ≠ pattern[j], then
         break
   if j == patLen, then
   display the position i, as there pattern found
End

Example

 Live Demo

#include <stdio.h>
#include <string.h>
int main (){
   char txt[] = "tutorialsPointisthebestplatformforprogrammers";
   char pat[] = "a";
   int M = strlen (pat);
   int N = strlen (txt);
   for (int i = 0; i <= N - M; i++){
      int j;
      for (j = 0; j < M; j++)
         if (txt[i + j] != pat[j])
      break;
      if (j == M)
         printf ("Pattern matches at index %d 
", i);    }    return 0; }

Output

Pattern matches at 6
Pattern matches at 25
Pattern matches at 39

Updated on: 24-Dec-2019

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements