You are on page 1of 3

Worksheet 3.

3
Student Name: Shaurav Suman Kumar UID: 19BCS2201
Branch: BE-CSE Section/Group: 8/C
Semester: 5th Date: 17-11-2021
Subject Name: Design and Analysis of Algorithms Lab Subject Code: CSP-309

Aim: Code and analyze to find all occurrence of pattern P in a given string S.

Algorithm:-
Naïve pattern searching algorithm is used to perform this experiment.
• Slide the pattern over text one by one and check for a match.
• If a match is found, then slides by 1 again to check for subsequent matches.

Code:-
#include <stdio.h>
#include <string.h>

// to find all the occurance of a pattern P in a given string S void


search(char* P, char* S)
{
int m = strlen(P);
int n = strlen(S);
int i, j;
printf("Given string is : '%s'\n", S);
// an outer loop to slide P[] one by one
for(i = 0; i <= n - m; i++)
{
// an inner loop to check for pattern match, for current index i
for (j = 0; j < m; j++) if (S[i + j] != P[j]) break;

if (j == m) // if P[0...m-1] = S[i, i+1, ... i+m-1]


printf("Pattern - '%s' is found at position %d.\n", P, i+1);
}
}

// main() to test the above code int


main()
{
printf("My uid is 19BCS2206\n\n");
char S[] = "This is an occurence of pattern in a string searching code."; char
P[] = "in"; // searched for "an" pattern as well for extra output snapshot
search(P, S); return 0;
}
Output snapshot:-

Complexities:-
The best case occurs when the first character of the pattern is not present in text at all. The
number of comparisons in best case is O(n).
The worst case of Naive Pattern Searching occurs in following scenarios.

• When all characters of the text and pattern are same.


• When only the last character is different.
The number of comparisons in the worst case is O(m*(n-m+1)).

Learning Outcomes:-

• I have learnt about searching all the occurrence of a pattern in a string


using Naïve pattern searching algorithm.
• I have learnt and analyzed about the space and time complexity of the
algorithm applied.

You might also like