【发布时间】:2018-03-10 21:03:35
【问题描述】:
我无法在逻辑上全神贯注地做这件事。我已经列出了排序的所有可能性,并以此为基础。
ABC
ACB
BAC
BCA
驾驶室
CBA
3 个字符串只有六种可能的组合,因此,我认为使用条件对其进行硬编码是一种非常快速且简单的解决方案。见代码;
char str1[x]; // where x is some constant value
char str2[x];
char str3[x];
char temp[x];
if (strcmp(str1, str2) > 0)
{
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
}
else if (strcmp(str2, str3) > 0)
{
strcpy(temp, str2);
strcpy(str2, str3);
strcpy(str3, temp);
}
else if (strcmp(str1, str3) > 0)
{
strcpy(temp, str1);
strcpy(str1, str3);
strcpy(str3, temp);
}
基本上,我想以 ABC 的任何变体为例,并将其分类为 ABC。即 BAC -> ABC,CAB -> ABC。
【问题讨论】:
-
1) 你的问题是什么? 2)正如你所说,有六种不同的可能性,但你的代码只能采用四种不同的执行路径(它运行第一个 if 块,第二个,第三个,或者都不运行)。这不是一个好兆头。
-
我认为你不需要
elses。 -
删除
else使其适用于除 CBA 和 BCA 之外的所有内容
标签: c sorting strcmp strcpy lexicographic