Skip to content

Commit

Permalink
Merge pull request ephremdeme#273 from Kanhakhatri065/master
Browse files Browse the repository at this point in the history
Implemented Suffix Array in C++
  • Loading branch information
Kanhakhatri065 authored Oct 3, 2020
2 parents 08805f8 + 8092807 commit 5bbd79c
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions Algorithms/SuffixArray.cpp
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;
}

0 comments on commit 5bbd79c

Please sign in to comment.