【发布时间】:2026-01-24 14:55:02
【问题描述】:
我正在处理一个编码问题,我必须按单词的长度对单词数组(指向字符串的指针)进行排序。我对使用一些索引操作的代码有一个想法,但希望在检查逻辑方面得到一些帮助,看看我是否有这个权利。这是我到目前为止的代码。
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()几乎什么都不做。 -
哦,我应该传入数组并在进行交换时通过引用它们来交换数组的值吗?
-
我对时间复杂性 atm 并不挑剔。也许稍后我会尝试重新设计 O(N) 。我可以使用指针,保存单词的数组是指针数组 (char**) 还是指向字符串的指针数组?我想我应该这么说
标签: c arrays algorithm sorting string-length