-
Notifications
You must be signed in to change notification settings - Fork 0
/
Suffix Array code
84 lines (84 loc) · 1.5 KB
/
Suffix Array code
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <bits/stdc++.h>
#define N '\n'
#define ll long long
#define L size()
using namespace std;
struct suffix
{
int ind;
char *suff;
};
int compare(struct suffix a,struct suffix b)
{
if(strcmp(a.suff,b.suff)<0)
{
return 1;
}
else
{
return 0;
}
}
int *buildarray(char *text,int n)
{
struct suffix suffixes[n];
for(int i=0;i<n;i++)
{
suffixes[i].ind=i;
suffixes[i].suff=(text+i);
}
sort(suffixes,suffixes+n,compare);
int *suffixarr=new int[n];
for(int i=0;i<n;i++)
{
suffixarr[i]=suffixes[i].ind;
}
return suffixarr;
}
void seapat(char *pat,char *txt,int *suffixarr,int n)
{
int len=strlen(pat);
int l=0,r=n-1;
while(l<=r)
{
int mid=(l+r)/2;
int res=strncmp(pat,txt+suffixarr[mid],len);
if(res==0)
{
cout<<"Pattern found at index "<<suffixarr[mid]<<N;
return;
}
if(res<0)
{
r=mid-1;
}
else
{
l=mid+1;
}
}
cout<<"Pattern not found"<<N;
}
void printArr(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<N;
}
int main()
{
cout<<"Enter the text"<<N;
char text[100];
cin>>text;
cout<<"Enter the pattern"<<N;
char pat[100];
cin>>pat;
int n=strlen(text);
int *suffixarr=buildarray(text,n);
cout<<"Sorted Index\n";
printArr(suffixarr,n);
seapat(pat,text,suffixarr,n);
return 0;
}