0% found this document useful (0 votes)
10 views1 page

Rabin Karp

The document contains a C program that implements the Rabin-Karp algorithm for string searching. It defines a function to search for a pattern within a given text using hashing and prints the index where the pattern is found. The main function initializes a sample text and pattern, then calls the search function with a prime number for hashing.

Uploaded by

saishj40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1 page

Rabin Karp

The document contains a C program that implements the Rabin-Karp algorithm for string searching. It defines a function to search for a pattern within a given text using hashing and prints the index where the pattern is found. The main function initializes a sample text and pattern, then calls the search function with a prime number for hashing.

Uploaded by

saishj40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <stdio.

h>
#include <string.h>
#define d 256

void search(char pat[], char txt[], int q) {


int M = strlen(pat);
int N = strlen(txt);
int i, j;
int p = 0;
int t = 0;
int h = 1;

for (i = 0; i < M - 1; i++)


h = (h * d) % q;

for (i = 0; i < M; i++) {


p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}

for (i = 0; i <= N - M; i++) {


if (p == t) {
for (j = 0; j < M; j++) {
if (txt[i + j] != pat[j])
break;
}
if (j == M)
printf("Pattern found at index %d \n", i);
}
if (i < N - M) {
t = (d * (t - txt[i] * h) + txt[i + M]) % q;
if (t < 0)
t += q;
}
}
}

int main() {
char txt[] = "THIS IS TEST TEXT";
char pat[] = "TEXT";
int q = 101;
search(pat, txt, q);
return 0;
}

You might also like