c - 如何在不使用 qsort 的情况下在 C 中实现后缀数组?
问题描述
我搜索了 C 中后缀数组的实现,但我看到的所有程序都是使用排序的 C++。我不确定如何使用 C 的内置函数 qsort() 代替 C 的 sort() 函数。我们可以在不使用 qsort() 的情况下实现后缀数组吗?或者如何使用 qsort() 在 C 中实现后缀数组?
这是我从 geeksforgeeks.com 获得的代码:
int cmp(struct suffix a, struct suffix b)
{
return strcmp(a.suff, b.suff) < 0? 1 : 0;
}
int *buildSuffixArray(char *txt, int n)
{
// A structure to store suffixes and their indexes
struct suffix suffixes[n];
// Store suffixes and their indexes in an array of structures.
// The structure is needed to sort the suffixes alphabatically
// and maintain their old indexes while sorting
for (int i = 0; i < n; i++)
{
suffixes[i].index = i;
suffixes[i].suff = (txt+i);
}
// Sort the suffixes using the comparison function
// defined above.
sort(suffixes, suffixes+n, cmp);
// Store indexes of all sorted suffixes in the suffix array
int *suffixArr = new int[n];
for (int i = 0; i < n; i++)
suffixArr[i] = suffixes[i].index;
// Return the suffix array
return suffixArr;
}
cmp 函数正在比较结构数据类型,而我在使用 qsort() 时遇到错误,表示只允许 void 输入。
解决方案
函数的声明qsort
如下:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
您会注意到,它接受的比较函数必须定义为const void *
对它的两个参数中的每一个都采用 a ,但您是在struct suffix
为每个参数传入 a 。
您需要更改比较函数以使用qsort
预期的参数类型。然后,您可以将函数内部的这些参数转换为正确的指针类型并使用它们。
int cmp(const void *p1, const void *p2)
{
const struct suffix *a = p1;
const struct suffix *b = p2;
return strcmp(a->suff, b->suff) < 0? 1 : 0;
}
推荐阅读
- delphi - 在 DUnitX 中一次运行所有测试用例
- swift - 在 swift collectionView 上遇到分页问题
- git - Gitlab错误消息:远程:HTTP基本:访问被拒绝致命:在docker-compose build上运行npm install时身份验证失败
- reactjs - 离子反应钩形式
- asynchronous - Typescript 中的流控制
- reactjs - Reactjs Onclick 按钮按天、月或年排序?
- html - 4k 分辨率的网站缩放以适应较小的窗口
- reactjs - TypeError: state.items 不可迭代 React-Redux
- angular - 使用 Typescript 2.6 运行 Angular 5 应用程序的最低浏览器支持
- sql - 如何在列中的字符和数字之间进行排序