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长度稳定排序所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)