按c长度稳定排序

按c长度稳定排序,第1张

概述我正在编写一个编码问题,我必须按字长来排序一个单词数组(指向字符串的指针).我知道使用一些索引 *** 作的代码,但是想要检查逻辑以查看我是否正确.这是我到目前为止的代码. void len_sort(char** words, int num_words){ int index=0; int isSorted=0; int string1_len; int string 我正在编写一个编码问题,我必须按字长来排序一个单词数组(指向字符串的指针).我知道使用一些索引 *** 作的代码,但是想要检查逻辑以查看我是否正确.这是我到目前为止的代码.

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;}

我不需要按字母顺序排序,我需要保持单词在数组中的顺序.例如:如果我有类似的东西

carxhorsea

我的输出应该如下:

xacarhorse

保持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长度稳定排序所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1227925.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存