我正在解决一个编码问题,需要按单词长度对字符串指针数组进行排序。我有一个使用索引操作的代码想法,但希望得到一些帮助来检查逻辑是否正确。以下是我的代码:
void len_sort(char** words, int num_words)
{
int index=0;
int isSorted=0;
int string1_len;
int string2_len;
while(isSorted==0)
{
for(index=0;index<num_words;index++)
{
printf("%s\n", words[index]);
string1_len=strlen(words[index]);
if((index+1)==num_words)
string2_len=strlen(words[index]);
else
string2_len=strlen(words[index+1]);
if(string1_len<string2_len)
{
swap(words[index], words[index+1]);
}
}
isSorted=1;
for(index=0;index<num_words;index++)
{
string1_len=strlen(words[index]);
if(index+1==num_words)
string2_len=strlen(words[index]);
else
string2_len=strlen(words[index+1]);
if(string1_len>string2_len)
{
isSorted=0;
}
}
}
}
void swap(char* word1, char* word2)
{
char* temp;
word1=word2;
word2=temp;
}
我可以不按字母顺序排序,需要保持单词在数组中的顺序。例如:如果我有以下内容:
car
x
horse
a
我的输出应该像这样:
x
a
car
horse
保持x在数组中在a之前的事实是正确的。 是否有更好的方法来提高这种排序的效率?
swap()
函数几乎什么也没做。 - MikeCATchar []
类型,并且可能需要将最大单词长度传递到交换函数中,以便可以分配正确数量的内存。 - Mike -- No longer here