C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了按c长度稳定排序大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写一个编码问题,我必须按字长来排序一个单词数组(指向字符串的指针).我知道使用一些索引操作的代码,但是想要检查逻辑以查看我是否正确.这是我到目前为止的代码.

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之前是真的.
有没有更好的方法来使用这种方法来提高效率?

解决方法

交换功能没有做任何有意义的事情.如果要交换两个指针,它应该是这样的

void swap(char **word1,char **word2)
{
    char *temp;

    temp = *word1;
    *word1 = *word2;
    *word2 = temp;

}

现在,为了稳定排序,我们只能交换前一个是否比下一个长.每次交换后,数组将更加分类一步.我们从一开始就开始

void len_sort(char** words,int num_words)
{
    int i = 0; //start from the beginning.
    while(i < num_words-1) //till the last pair.
    {
        if(strlen(words[i]) > strlen(words[i+1])){//if a mismatch occur
            swap(&words[i],&words[i+1]);//fix it
            i = -1;//and start from the beginning 
        }
        i++;//so far sorted,try next pair
    }
}

测试:

int main()
{
    char d[][30] = {"car","x","horse","a"};
    char *s[4];
    int i;

    //our function sort through pointer
    for(i=0; i<4; i++)
        s[i] = d[i];

    len_sort(s,4);
    for(i=0; i<4; i++)
        printf("%s ",s[i]);
    puts("");

    return 0;
}

OUTPUT:

x a car horse

大佬总结

以上是大佬教程为你收集整理的按c长度稳定排序全部内容,希望文章能够帮你解决按c长度稳定排序所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。