forked from ephremdeme/data-structure-and-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request ephremdeme#273 from Kanhakhatri065/master
Implemented Suffix Array in C++
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
#include <iostream> | ||
#include <algorithm> | ||
#include <cstring> | ||
|
||
using namespace std; | ||
|
||
struct suffix{ | ||
int index; | ||
char *suff; | ||
}; | ||
|
||
int cmp(struct suffix a, struct suffix b) { | ||
return strcmp(a.suff, b.suff) < 0 ? 1: 0; | ||
} | ||
|
||
int *buildSuffixArray(char *txt, int n) { | ||
struct suffix suffixes[n]; | ||
|
||
for(int i = 0;i < n;i++) { | ||
suffixes[i].index = i; | ||
suffixes[i].suff = (txt + i); | ||
} | ||
|
||
sort(suffixes, suffixes + n, cmp); | ||
|
||
int *suffixArr = new int[n]; | ||
for(int i = 0;i < n;i++) { | ||
suffixArr[i] = suffixes[i].index; | ||
} | ||
|
||
return suffixArr; | ||
} | ||
|
||
void printArr(int arr[], int n) { | ||
for(int i = 0;i < n;i++) { | ||
cout << arr[i] << " "; | ||
} | ||
cout << endl; | ||
} | ||
|
||
int main() { | ||
char txt[] = "banana"; | ||
int n = strlen(txt); | ||
int *suffixArr = buildSuffixArray(txt, n); | ||
cout << "Following is suffix array for " << txt << endl; | ||
printArr(suffixArr, n); | ||
|
||
return 0; | ||
} |