Professional Documents
Culture Documents
Experiment No.09
A.1 Aim:
Write a program to implement naïve string matching algorithm.
A.2 Prerequisite:
A.3 Outcome:
A.4 Theory:
The idea of the naive solution is just to make a comparison character by character of the
text T[s...s + m − 1] for all s ∈ {0, . . . , n − m + 1} and the pattern P[0...m − 1]. It returns
all the valid shifts found.
Algorithm:
NAIVE-STRING-MATCHER(T, P)
n length[T]
m length[P]
for s 0 to n - m
do if P[1 . . m] = T[s + 1 . . s + m]
then print "Pattern occurs with shift" s
Example:
Time Complexity:
The time complexity of the Naive algorithm in its worst case is O(M × N). For example if
the pattern to search is a m and the text is a n, then we need M operation of comparison
by shift. For all the text, we need (N − M + 1) × M operation, generally M is very small
compared to N, it is why we can simply considered the complexity as O(M × N).
PART B
(PART B : TO BE COMPLETED BY STUDENTS)
(Students must submit the soft copy as per following segments within two hours of the
practical. The soft copy must be uploaded on the Blackboard or emailed to the concerned lab in
charge faculties at the end of the practical in case the there is no Black board access available)
Code:-
#include<stdio.h>
#include<string.h>
int main()
{
char Text[100],Pattern[100];
int status;
B.4 Conclusion:
(Students must write the conclusion as per the attainment of individual outcome listed above and
learning/observation noted in section B.3)
Q.2: Why naïve string matching algorithm is not said to be an efficient algorithm?
Ans:-
The number of comparisons in the worst case is O(m*(n-m+1)). Although strings which have repeated
characters are not likely to appear in English text, they may well occur in other applications (for example,
in binary texts). The KMP matching algorithm improves the worst case to O(n). We will be covering KMP
in the next post. Also, we will be writing more posts to cover all pattern searching algorithms and data
structures.
Ans:- It is used for sorting a string which is being sent by the user.
************************