【问题标题】:How to implement suffix array in C without using qsort?如何在不使用 qsort 的情况下在 C 中实现后缀数组?
【发布时间】:2020-12-04 15:36:42
【问题描述】:

我在C中搜索了后缀数组的实现,但是我看到的所有程序都是使用排序的C++。我不确定如何使用 C 的内置函数 qsort() 代替 C 的 sort() 函数。 我们可以在不使用 qsort() 的情况下实现后缀数组吗? 或者 C语言中如何使用qsort()实现后缀数组?

这是我从 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
  • 您使用 qsort() 的方式与在任何其他上下文中使用它的方式相同,后缀数组有什么不同?
  • 听起来您只是不确定如何使用qsort() 对结构数组进行排序。
  • 那么你能指导我如何使用 qsort
  • 首先阅读man page。这描述了它的工作原理并有一个示例,因此应该可以帮助您入门。

标签: c suffix-array


【解决方案1】:

qsort函数的声明如下:

void qsort(void *base, size_t nmemb, size_t size,
       int (*compar)(const void *, const void *));

您会注意到,它接受的比较函数必须定义为对其两个参数中的每一个都采用 const void *,但您要为每个参数传入 struct suffix

您需要更改比较函数以使用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; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    相关资源
    最近更新 更多