已知字母序列【d, g, e, c, f, b, o, a】,请实现一个函数针对输入的一组字符串 input[] = {"bed", "dog", "dear", "eye"},按照字母顺序排序并打印。
本例的输出顺序为:dear, dog, eye, bed。
#include <string>
#include <stdlib.h>
using namespace std;
int compare(char *str1, char *str2, int *hash)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
int i = 0;
int j = 0;
while (i < len1&&j < len2)
{
if (hash[str1[i]] < hash[str2[j]])
{
return 1;
}
else if (hash[str1[i]] > hash[str2[j]])
{
return -1;
}
else
{
i++;
j++;
}
}
if (i == len1&&j == len2)
{
return 0;
}
else if (i == len1)
{
return -1;
}
else if (j == len2)
{
return 1;
}
}
void print(char **s, int len)
{
int i;
for (i = 0; i < len; i++)
{
printf("%s ", *(s+i));
}
}
int main()
{
char *s[4] = { "bed", "dog", "dear", "eye" };
char *h = "dgecfboa";
int i;
int j;
int cnt = 0;
int len = strlen(h);
int hash[256];
while (*h != '\0')
{
hash[*h] = cnt++;
h++;
}
for (i = 0; i < 3; i++)
{
int max = i;
for (j = i+1; j < 4; j++)
{
if (compare(s[max], s[j], hash) == -1)
{
max = j;
}
}
char *t = s[i];
s[i] = s[max];
s[max] = t;
}
print(s, 4);
}