Skip to content

Instantly share code, notes, and snippets.

@cls
Last active December 30, 2017 21:17
Show Gist options
  • Save cls/865f67c792e1a686b26a346783abfaf8 to your computer and use it in GitHub Desktop.
Save cls/865f67c792e1a686b26a346783abfaf8 to your computer and use it in GitHub Desktop.
Constructing a simple suffix array
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int pstrcmp(const void *, const void *);
int
main(void)
{
char buf[BUFSIZ];
if (!fgets(buf, sizeof buf, stdin))
return 1;
size_t len = strlen(buf);
const char *array[len];
for (size_t i = 0; i < len; i++)
array[i] = &buf[i];
qsort(array, len, sizeof *array, pstrcmp);
for (size_t i = 0; i < len; i++)
printf("%tu\n", array[i] - buf);
return 0;
}
int
pstrcmp(const void *p1, const void *p2)
{
const char *const *s1 = p1;
const char *const *s2 = p2;
return strcmp(*s1, *s2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment