Created
April 22, 2019 12:35
-
-
Save torus/fd6a3efee36c76e6ed2aaa7c9a6856c0 to your computer and use it in GitHub Desktop.
Suffix Array
This file contains hidden or 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int compar(const void* a, const void* b) { | |
return strcmp(*(const char**)a, *(const char**)b); | |
} | |
int main(int argc, char** argv) { | |
const char *giantString = | |
"Lorem ipsum dolor sit amet," | |
" consectetur adipiscing elit," | |
" sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; | |
// Creating a suffix array from the "giant" string | |
const size_t size = strlen(giantString); | |
const char **suffixArray = (const char**)malloc(size * sizeof(char*)); | |
for (int i = 0; i < size; i ++) { | |
suffixArray[i] = &giantString[i]; | |
} | |
qsort(suffixArray, size, sizeof(char*), compar); | |
// Let's search a string "tempo" | |
const char *key = "tempo"; | |
// Binary search | |
const char **p1 = suffixArray; | |
const char **p2 = suffixArray + size; | |
while (p1 < p2 - 2) { | |
const char **m = p1 + (p2 - p1) / 2; | |
if (strcmp(*m, key) > 0) { | |
p2 = m + 1; | |
} else { | |
p1 = m; | |
} | |
} | |
printf("found: %s\n", *(p2 - 1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment