The presenation gives a brief detail about a searching algorithm known as "Rabin-Karp Algorithm". The presentation contains the history of the algorithm and its working alongwith the example.
2. INTRODUCTION:-
Rabin–Karp algorithm or Karp–Rabin algorithm is a string
searching algorithm created by Richard M.Karp and Michael
O.Rabin (1987) .
Richard Manning Karp
Born: January 3, 1935
Michael Oser Rabin
Born: September 1, 1931
3. EXAMPLE:-
Rabin–Karp algorithm or Karp–Rabin algorithm is a string
searching algorithm that uses hashing to find any one of a set of
pattern strings in a text.
DEFINITION:-
Text: [3141592653………………9451] Total size =97
Pattern: 59265
Output:-
59265 found at point [5].
4. WORKING:-
Rabin-Karp algorithm makes small pieces of the statement according to the size of the
pattern we want to find.
Let’s take the example shown in the previous slide.
Text T (3141592653………………9451)
Hash H(ninety seven)
Pattern P(59265)
59265 % 97=95
P mod H
6. CODE :-
#define d 10
void RabinKarpStringMatch(char *Text, char *Pattern, int Number)
{
int M,N,h,P=0,T=0, TempT, TempP;
int i,j;
M = strlen(Pattern);
N = strlen(Text);
h = (int)pow(d,M-1) % Number;
for(i=0;i<M;i++)
{
P = ((d*P) + ((int)Pattern[i])) % Number;
TempT = ((d*T) + ((int)Text[i]));
T = TempT % Number;
}
for(i=0;i<=N-M;i++) {
// d has value 10
// initializing some integers
// hashing formula
// outer for loop
// Inner for loop
7. for(i=0;i<=N-M;i++)
{
if(P==T)
{
for(j=0;j<M;j++)
if(Text[i+j] != Pattern[j])
break;
if(j == M)
printf("nPattern Found at Position : %d",i+1);
TempT =((d*(T - Text[i]*h)) + ((int)Text[i+M]));
T = TempT % Number;
if(T<0)
T=T+Number;
}
// Another inner for loop
// if statement works if pattern is found in the text
// Third inner for loop
// If this is statement gets true then
its body prints the pattern position.