-
Notifications
You must be signed in to change notification settings - Fork 0
/
BoyerMoore.c
59 lines (52 loc) · 1.13 KB
/
BoyerMoore.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <string.h>
#define LEN 256
int max(int a, int b)
{
return (a > b) ? a : b;
}
void badCharHeuristic(char *str, int size, int badchar[LEN])
{
int i;
for (i = 0; i < LEN; i++)
badchar[i] = -1;
for (i = 0; i < size; i++)
badchar[(int)str[i]] = i;
}
int search(char *txt, char *pat)
{
int m = strlen(pat);
int n = strlen(txt);
int badchar[LEN];
badCharHeuristic(pat, m, badchar);
int s = 0;
while (s <= (n - m))
{
int j = m - 1;
while (j >= 0 && pat[j] == txt[s + j])
j--;
if (j < 0)
{
// printf("Pattern occurs at shift = %d\n", s);
return s;
}
else
s += max(1, j - badchar[(int)txt[s + j]]);
}
return -1; // Pattern not found
}
int main()
{
char txt[100], pat[20];
int pos;
printf("Enter the text: ");
scanf("%s", txt);
printf("Enter the pattern: ");
scanf("%s", pat);
pos = search(txt, pat);
if (pos < 0)
printf("Pattern not found\n");
else
printf("Pattern found at position %d\n", pos);
return 0;
}