【问题标题】:Lexicographic sort using provided character set使用提供的字符集进行字典排序
【发布时间】:2021-09-03 12:23:19
【问题描述】:

我了解执行字典排序背后的逻辑以及如何以简单的方式对其进行编码。当看到这个函数签名时,我不知道该怎么做

void sort_lexicographically(char *phrase, char const *alphabet);

其中两个参数都是字符串。

【问题讨论】:

标签: arrays c sorting


【解决方案1】:

鉴于函数签名,对于函数应该做什么只有一种合理的解释:根据alphabet 定义的排序顺序对字符串phrase 中的字符进行就地排序。这可以做到 e。 G。带有一个包含每个字符的排序位置的表格。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

char ord[CHAR_MAX-CHAR_MIN+1];

int compar(const void *a, const void *b)
{
    return ord[*(char *)a-CHAR_MIN]-ord[*(char *)b-CHAR_MIN];
}

void sort_lexicographically(char *phrase, char const *alphabet)
{
    memset(ord, 0, sizeof ord); // all characters not in alphabet get order 0
    int o = 0;  // collating order, increasingly assigned to alphabet characters
    while (*alphabet) ord[*alphabet++-CHAR_MIN] = ++o;
    qsort(phrase, strlen(phrase), 1, compar);
}

int main()
{
    char phrase[] = "the quick brown fox jumps over the lazy dog";
    puts(phrase);
    sort_lexicographically(phrase, "aeioubcdfghjklmnpqrstvwxyz");
    puts(phrase);
}

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    相关资源
    最近更新 更多