【问题标题】:Parallel sort two arrays并行排序两个数组
【发布时间】:2015-02-04 20:07:51
【问题描述】:

假设我有两个数组:

char **words = (char**) malloc(MAX * sizeof(char*));
int *count = malloc(MAX * sizeof(int));

第一个将单词存储在给定列表中:

words[0] = "myword0" / words[1] = "myword1" / words[2] = "myword3" ...

第二个存储列表中每个单词的出现次数:

count[0] = 4 //means that "myword0" appears 4 times in the list

我想打印最常见的单词及其出现次数。 如果有出现相同次数的单词,按字母顺序打印第一个

为此,我考虑按字母顺序对单词进行排序:

int sortWordsAlph(const void* a, const void* b)
{
    char **x = (char**)a;
    char **y = (char**)b;

    return (strcmp(*x,*y));
}

int main():

qsort(words, MAX, sizeof(char*), sortWordsAlph);

现在,问题在于 count。它仍然应该指向每个单词的出现,这意味着我也必须对其进行排序。我怎样才能做到这一点?

也许我应该使用交换算法而不是 qsort?

【问题讨论】:

  • 如果您使用的是库 qsort,您似乎必须对结合了单词指针和计数的结构数组进行排序。如果您使用自己的自定义 qsort,则可以同时交换两个数组元素。
  • 这可以通过另一个表(数组)来解决,其中包含其他表的索引。然后你可以将它传递给排序函数,并使用索引来查找实际的字符串和计数。
  • 也可以通过多次排序完成;一次按频率排序,然后多次按字母顺序对频率相同的单词进行排序。
  • @500-InternalServerError - 所以,每当我交换 words 的 i,j 元素时,我应该交换 count 的相同 i,j 元素,对吗?
  • 是的,我就是这个意思。

标签: c arrays string sorting char


【解决方案1】:

如果你想使用qsort(),你应该使用一个包含单词和计数的结构数组。然后,您可以使用自定义比较函数将您的数组传递给 qsort()

struct wc_s {
  char *word;
  int count;
};

int cmp_words (const void *p1, const void *p2)
{
   const struct wc_s *s1 = p1;
   const struct wc_s *s2 = p2;
   return strcmp (s1->word, s2->word);
}

int cmp_counts (const void *p1, const void *p2)
{
   const struct wc_s *s1 = p1;
   const struct wc_s *s2 = p2;
   return s2->count - s1->count;
}

...
struct wc_s *wc_list = malloc (MAX * sizeof *wc_list);
...
qsort (wc_list, MAX, sizeof *wc_list, cmp_counts);

如果保证qsort() 执行稳定排序(即比较相同的两个元素保留其原始顺序),您可以通过首先按单词排序,然后按计数排序来解决您的问题。不幸的是,两个相等元素的结果顺序是未指定

你可以做的是按计数对数组进行排序,然后通过数组找到具有相同计数的子数组,并分别对它们进行排序:

int start = 0;
int length;
while (start < MAX) {
  for (length = 1; start+length < MAX; length++) {
    if (wc_list[start].count != wc_list[start+length].count)
      break;
  }
  qsort (wc_list+start, length, sizeof *wc_list, cmp_words);
  start += length;
}

【讨论】:

  • 我使用了一个结构来保存我的单词及其频率,然后我按大小对其进行了排序;每当我有出现相同次数的单词时,我都会按字母顺序对它们进行排序,这正是我想要的!
猜你喜欢
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多